您可以提供自定义的 AuthenticationSuccessHandler. AuthenticationSuccessHandler 告诉 Spring Security 在用户身份验证成功后要做什么. 默认实现通常使用 SimpleUrlAuthenticationSuccessHandler,一旦用户成功通过身份验证,它会将用户重定向到提供的 URL.
You can supply a custom AuthenticationSuccessHandler.
The AuthenticationSuccessHandler is what tells Spring Security what to do after a successful user authentication.
The default implementation typically uses a SimpleUrlAuthenticationSuccessHandler, which redirects users to the supplied URL once they successfully authenticate.
In your custom implementation, you can delegate to a different SimpleUrlAuthenticationSuccessHandler based on the user's role.
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
SimpleUrlAuthenticationSuccessHandler userSuccessHandler =
new SimpleUrlAuthenticationSuccessHandler("/user-page");
SimpleUrlAuthenticationSuccessHandler adminSuccessHandler =
new SimpleUrlAuthenticationSuccessHandler("/admin-page");
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
for (final GrantedAuthority grantedAuthority : authorities) {
String authorityName = grantedAuthority.getAuthority();
if (authorityName.equals("ROLE_ADMIN")) {
// if the user is an ADMIN delegate to the adminSuccessHandler
this.adminSuccessHandler.onAuthenticationSuccess(request, response, authentication);
return;
}
}
// if the user is not an admin delegate to the userSuccessHandler
this.userSuccessHandler.onAuthenticationSuccess(request, response, authentication);
}
}
然后,在表单登录配置中提供CustomAuthenticationSuccessHandler.
Then, supply the CustomAuthenticationSuccessHandler in the form login configuration.