Spring security认证流程
Spring Security 认证流程大致如下:
- 用户提交登录表单,请求发送至
/login
路径。 - Spring Security 处理
/login
路径,通过配置的AuthenticationEntryPoint
(默认是LoginUrlAuthenticationEntryPoint
)重定向到登录页面。 - 用户输入凭证并提交,请求发送至
/login
路径。 - Spring Security 通过配置的
AuthenticationManager
处理认证请求。 AuthenticationManager
通过ProviderManager
查询相应的AuthenticationProvider
来验证凭证。AuthenticationProvider
会进一步委托UserDetailsService
查询用户详情(包括权限等信息)。- 如果认证成功,
AuthenticationProvider
会生成一个包含用户详情的Authentication
对象。 ProviderManager
返回成功认证的Authentication
对象给AuthenticationManager
。AuthenticationManager
处理完毕后,通过配置的AuthenticationSuccessHandler
处理登录成功。- 如果认证失败,
AuthenticationManager
通过配置的AuthenticationFailureHandler
处理登录失败。
以下是一个简单的 Spring Security 配置示例,演示如何自定义登录流程:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
@Autowired
private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}user").authorities("ROLE_USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(customAuthenticationSuccessHandler)
.failureHandler(customAuthenticationFailureHandler);
}
}
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
// 登录成功后的操作
}
}
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
// 登录失败后的操作
}
}
在这个配置中,我们定义了一个 \`CustomAuthent
评论已关闭