Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure a web application with multiple realms using Spring's Java Config?

I have a web application with 2 types of resources.

  • web pages
  • web services

I want to secure the web pages using one authentication provider (i.e. CAS) and the web services using another authentication provider (i.e. BASIC authentication).

I found a solution which could work here, but it uses XML, and I would prefer to not use XML configuration if possible.

Is there a Java Config solution to this?

like image 250
Jin Kim Avatar asked Nov 21 '22 21:11

Jin Kim


1 Answers

Well it took a while to figure out how to do it...

Basically I split up my original security configuration class into 3 separate configuration classes.

This is basically how I did it...

The main security configuration...

@Configuration
@Import({WebPageSecurityConfig.class, WebServiceSecurityConfig.class})
public class SecurityConfig {
}

The security configuration for web pages... (URL does not begin with /service/**)

@Configuration
@Order(200)
@EnableWebMvcSecurity
public class WebPageSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(casAuthenticationProvider());
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();

        http.requestMatcher(new RequestMatcher() {
            @Override
            public boolean matches(final HttpServletRequest request) {
                final String url = request.getServletPath() + StringUtils.defaultString(request.getPathInfo());
                return !(url.startsWith("/service/"));
            }
 });
        http.addFilter(casAuthenticationFilter()).exceptionHandling().authenticationEntryPoint(casAuthenticationEntryPoint());
        http.authorizeRequests().
            antMatchers("/securedPage").hasAuthority("ROLE_CAS_USER"). // /securedPage can only be accessed by cas user
            anyRequest().permitAll(); // all other pages are unsecured
    }

    // General Application Security (CAS Authentication)

    @Bean
    public CasAuthenticationFilter casAuthenticationFilter() throws Exception {
        final CasAuthenticationFilter casAuthenticationFilter = new CasAuthenticationFilter();
        casAuthenticationFilter.setAuthenticationManager(authenticationManager());
        return casAuthenticationFilter;
    }

    @Bean
    public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {
        final CasAuthenticationEntryPoint casAuthenticationEntryPoint = new CasAuthenticationEntryPoint();
        casAuthenticationEntryPoint.setLoginUrl(env.getRequiredProperty("cas.server.url") + "/login");
        casAuthenticationEntryPoint.setServiceProperties(casServiceProperties());
        return casAuthenticationEntryPoint;
    }

    @Bean
    public ServiceProperties casServiceProperties() {
        final ServiceProperties serviceProperties = new ServiceProperties();
        serviceProperties.setService(env.getRequiredProperty("cas.service.url") + "/j_spring_cas_security_check");
        serviceProperties.setSendRenew(false);
        return serviceProperties;
    }

    @Bean
    public CasAuthenticationProvider casAuthenticationProvider() {
        final CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
        casAuthenticationProvider.setAuthenticationUserDetailsService(casAuthenticationUserDetailsService());
        casAuthenticationProvider.setServiceProperties(casServiceProperties());
        casAuthenticationProvider.setTicketValidator(casTicketValidator());
        casAuthenticationProvider.setKey("casAuthenticationProviderKey");
        casAuthenticationProvider.setStatelessTicketCache(casStatelessTicketCache());
        return casAuthenticationProvider;
    }

    @Bean
    public AuthenticationUserDetailsService casAuthenticationUserDetailsService() {
        final AbstractCasAssertionUserDetailsService authenticationUserDetailsService = new AbstractCasAssertionUserDetailsService() {

            @Override
            protected UserDetails loadUserDetails(final Assertion assertion) {
                final String username = assertion.getPrincipal().getName();
                final List<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority("ROLE_CAS_USER"));                
                return new User(username, "notused", authorities);
            }
        };

        return authenticationUserDetailsService;
    }

    @Bean
    public TicketValidator casTicketValidator() {
        final Saml11TicketValidator ticketValidator = new Saml11TicketValidator(env.getRequiredProperty("cas.server.url"));
        ticketValidator.setTolerance(env.getRequiredProperty("cas.ticket.tolerance", Long.class));
        return ticketValidator;
    }

    @Bean
    public StatelessTicketCache casStatelessTicketCache() {
        final EhCacheBasedTicketCache ticketCache =  new EhCacheBasedTicketCache();
        ticketCache.setCache(casCache());
        return ticketCache;
    }

    @Bean(initMethod = "initialise", destroyMethod = "dispose")
    public Cache casCache() {
        final Cache cache = new Cache("casTickets", 50, true, false, 3600, 900);
        return cache;
    }       

    @Autowired
    private Environment env;
}

The security configuration for RESTful web services (URL starts with /service/**)

@Configuration
@Order(300)
@EnableWebMvcSecurity
public class WebServiceSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().
            withUser("admin").password("password").authorities(new SimpleGrantedAuthority("ROLE_WS_USER"));
    }

    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();

        http.
            antMatcher("/service/**"). // only process URLs that begin with /service/
            sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and(). // RESTful web services are stateless
            addFilter(wsAuthenticationFilter()).exceptionHandling().authenticationEntryPoint(wsAuthenticationEntryPoint());

        http.authorizeRequests().anyRequest().hasAuthority("ROLE_WS_USER"); // all requests are secured
    }

    // Web Service Security (BASIC Authentication)

    @Bean
    public BasicAuthenticationFilter wsAuthenticationFilter() throws Exception {
        final BasicAuthenticationFilter wsAuthenticationFilter = new BasicAuthenticationFilter(authenticationManager(), wsAuthenticationEntryPoint());
        return wsAuthenticationFilter;
    }

    @Bean
    public BasicAuthenticationEntryPoint wsAuthenticationEntryPoint() {
        final BasicAuthenticationEntryPoint wsAuthenticationEntryPoint = new BasicAuthenticationEntryPoint();
        wsAuthenticationEntryPoint.setRealmName("My Realm");
        return wsAuthenticationEntryPoint;
    }

    @Autowired
    private Environment env;
}
like image 94
Jin Kim Avatar answered Nov 24 '22 11:11

Jin Kim