Spring security认证流程
warning:
这篇文章距离上次修改已过430天,其中的内容可能已经有所变动。
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
评论已关闭