Search This Blog

Wednesday, July 19, 2017

Spring Security Java Configuration Annotation Example

This application demonstrate how to use spring security in spring mvc application. This is java config annotation based configuration. I tried to implement following customization on spring security framework.

  1. Custom Authentication Provider.
  2. Custom UserDetailsService.
  3. Custom LoginSuccessHandler
  4. Custom AuthenticationFailureHandler
  5. Custom AccessDecisionVoter
  6. Update Current LoggedIn UserDetails
  7. Display All LoggedIn User In Application.
  8. Custom taglib to show/hide action based on user's role and permission.
  9. Prevent multiple login for same user (spring security concurrent user login prevention).
  10. Override spring security message as custom message.
  11. Expiring all Sessions of a LoggedIn Users.
  12. How to implement apache tiles template engine for multiple layout on JSP page.
 You can download source code from SpringSecurityMVC

@Configuration
@EnableWebSecurity
@ComponentScan("com.application")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    CustomAuthenticationProvider customAuthenticationProvider;

    @Autowired
    @Qualifier("secureUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    LoginSuccessHandler loginSuccessHandler;

    @Autowired
    LoginFailHandler loginFailHandler;

    public SecurityConfig() {
        super();
    }

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
        auth.authenticationProvider(customAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(UrlMapping.getLoginUrl(), UrlMapping.getSignInUrl())
                .permitAll()
                .anyRequest()
                .authenticated()
                .accessDecisionManager(accessDecisionManager())
                .and()
                    .formLogin()
                        .loginPage(UrlMapping.getLoginUrl())
                        .loginProcessingUrl(UrlMapping.getSignInUrl())
                        .failureUrl(UrlMapping.getSignInUrl())
                        .failureHandler(loginFailHandler)
                        .successHandler(loginSuccessHandler)
                        .usernameParameter("email").passwordParameter("password").and()
                        .exceptionHandling().accessDeniedPage(UrlMapping.getUnauthorizedUrl())
                .and()
                    .logout()
                        .logoutSuccessUrl("/")
                        .deleteCookies("JSESSIONID", "SESSION")
                        .invalidateHttpSession(true)
                .and()
                    .sessionManagement()
                        .sessionAuthenticationStrategy(concurrentSessionControlAuthenticationStrategy())
                        .maximumSessions(1)
                        .maxSessionsPreventsLogin(true)
                        .expiredUrl("/")
                        .sessionRegistry(sessionRegistry());

    }
   
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/resources/**");
//        super.configure(web);
    }

    @Bean
    PasswordEncoder encoder() {
        return new BCryptPasswordEncoder(15);
    }

    @Bean
    public AccessDecisionManager accessDecisionManager() {
        List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new WebExpressionVoter(),
                new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter());
        return new UnanimousBased(decisionVoters);
    }

    @Bean
    public SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }

    @Bean
    public HttpSessionEventPublisher httpSessionEventPublisher() {
        return new HttpSessionEventPublisher();
    }

    @Bean
    ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlAuthenticationStrategy() {
        ConcurrentSessionControlAuthenticationStrategy csca = new ConcurrentSessionControlAuthenticationStrategy(
                sessionRegistry());
        csca.setExceptionIfMaximumExceeded(true);
        csca.setMaximumSessions(1);
        return csca;
    }



No comments:

Post a Comment