1. 實現`AuthenticationSuccessHandler`接口
```java
@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Autowired
private ObjectMapper mapper;
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(mapper.writeValueAsString(authentication));
}
}
```
2. 修改`BrowserSecurityConfig`配置
```java
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.successHandler(myAuthenticationSuccessHandler) // 自定義登錄成功處理邏輯
.and()
.authorizeRequests()
.antMatchers("/login.html").permitAll()
.anyRequest()
.authenticated()
.and().csrf().disable();
}
}
```
###### 可以獲取到登錄成功后的認證信息
```java
SecurityContextHolder.getContext().getAuthentication()
```
同理,自定義登錄失敗可以實現`onAuthenticationFailure`接口。此文就不再演示。