Spring Security – Config Security for Web MVC by Spring Boot

preview_player
Показать описание

Spring Security – Customize Login Handler

Spring Security provides lots of API for handling our program, the tutorial will guide you how to Customize Login Handler.

For how to start with Spring Security, you can follow the link: Spring Security – Config Security for Web MVC by Spring Boot
Related article: Spring Security Customize Logout Handler

I. AuthenticationSuccessHandler for Customize Login Handler tutorial

interface AuthenticationSuccessHandler is strategy used to handle a successful user authentication.

Implementations can do whatever they want but typical behaviour would be to control the navigation to the subsequent destination (using a redirect or a forward). For example, after a user has logged in by submitting a login form, the application needs to decide where they should be redirected to afterwards (see
AbstractAuthenticationProcessingFilter and subclasses). Other logic may also be included if required.

II. Overview

1. Technologies

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.2.RELEASE

2. Project structure

3. Step to do

– Create a Spring Security step by step follow article: Spring Security – Config Security for Web MVC by Spring Boot
Main Part:
– Create a class that implements AuthenticationSuccessHandler
– Add successHandler config at: WebSecurityConfigurerAdapter

III. Practice

Create a CustomAuthenticationSuccessHandler that implement interface AuthenticationSuccessHandler by override function: onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) for developing the customize logic of application after login successfully.

With above code, after login successfully, application will check role of login user, if user has Admin role, it will be redirected to /admin url, otherwise it will be redirected to /welcome url

2. Add successHandler config at: WebSecurityConfigurerAdapter

In config class SecurityConfig extends WebSecurityConfigurerAdapter, inject CustomAuthenticationSuccessHandler bean. Then config successhandler: formLogin().successHandler(customAuthenticationSuccessHandler)

IV. Sourcecode

spring security customize login handler
Рекомендации по теме
visit shbcf.ru