可能重复:
Setting custom Post-Login Destinations based on user ROLES using spring security
我正在使用Spring在Java中完成我的项目。我在我的项目中使用spring security。
我的问题是,根据ROLE_USER或ROLE_ADMIN的角色,我想将它们重定向到不同的页面。 这意味着如果Admin已登录,那么他应该重定向到一个页面,如果普通用户登录到不同的页面,但两个用户的登录页面都相同。
现在我在spring-servlet.xml文件中使用下面的代码。所以请建议我解决这个问题。
<security:http auto-config="true">
<security:intercept-url pattern="/airline/*" access="ROLE_USER" />
<security:form-login login-page="/login" default-target-url="/logout"
authentication-failure-url="/login" />
<security:logout logout-success-url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSrc"
users-by-username-query="select username,password,enabled from spring_users where username=?"
authorities-by-username-query="select u.username, ur.authority from spring_users u, spring_roles ur where u.user_id=ur.user_id and u.username=?"/>
</security:authentication-provider>
</security:authentication-manager>
答案 0 :(得分:4)
如果要在成功验证后控制导航流,可以通过添加自己的AuthenticationSuccessHandler来实现。
将以下属性添加到引用customAuthenticationHandler bean的<form-login> element
,
<form-login login-page="/login.xhtml" authentication-success-handler-ref="customAuthenticationHandler"/>
...
</http>
<beans:bean id="customAuthenticationHandler" class="com.examples.CustomAuthenticationHandler" />
CustomAuthenticationHandler类如下所示:
public class CustomAuthenticationHandler extends SimpleUrlAuthenticationSuccessHandler{
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
String userTargetUrl = "/welcome.xhtml";
String adminTargetUrl = "/admin/welcome.xhtml";
Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
if (roles.contains("ROLE_ADMIN")) {
getRedirectStrategy().sendRedirect(request, response, adminTargetUrl);
}
else if(roles.contains("ROLE_USER")) {
getRedirectStrategy().sendRedirect(request, response, userTargetUrl);
}
else {
super.onAuthenticationSuccess(request, response, authentication);
return;
}
}
}