您可以重新定义 Spring Security 身份验证成功处理程序
创建一个实现 AuthenticationSuccessHandler 的类:
public class RoleBasedAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
//Store the role and destination url relationship
private static Map<String, String> ROLE_URL_MAP = new HashMap<String, String>();
static {
ROLE_URL_MAP.put("ROLE_AUDIT", "/private/auditindex.do");
ROLE_URL_MAP.put("ROLE_USER", "/private/userindex.do");
ROLE_URL_MAP.put("ROLE_ADMIN", "/private/adminindex.do");
}
private static String DEFAULT_URL = "/private/home.do";
/**
* {@inheritDoc}
*/
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
if (authentication.getPrincipal() instanceof UserDetails) {
//obtain the userDetails
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
//rediret to destination url
response.sendRedirect(request.getContextPath() + getTargetUrl(userDetails));
} else {
//rediret to default url
response.sendRedirect(request.getContextPath() + DEFAULT_URL);
}
}
/**
* get de target Url for roluser
* @param userDetails userDetails
* @return target url after login
*/
public static String getTargetUrl(UserDetails userDetails) {
String role = userDetails.getAuthorities().isEmpty() ? null : userDetails.getAuthorities().toArray()[0].toString();
String targetUrl = ROLE_URL_MAP.get(role);
if (targetUrl != null) {
return targetUrl;
} else {
return DEFAULT_URL;
}
}
}
如果你使用 xml-confi,你定义你的 bean:
<beans:bean id="redirectRoleStrategy" class="xxx.xxx.RoleBasedAuthenticationSuccessHandler"/>
和
<security:form-login authentication-success-handler-ref="redirectRoleStrategy">
但是如果你使用 java-config 包含在 WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().successHandler(new RoleBasedAuthenticationSuccessHandler());
}