可能的重复:
使用 spring security 根据用户角色设置自定义登录后目标 https://stackoverflow.com/questions/2818055/setting-custom-post-login-destinations-based-on-user-roles-using-spring-security
我正在使用 Spring 在 Java 中完成我的项目。我在我的项目中使用 spring security。
我的问题是,根据 ROLE_USER 或 ROLE_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>
如果您想在身份验证成功后控制导航流程,可以通过添加自己的 AuthenticationSuccessHandler 来实现。
将以下属性添加到您的<form-login> element
它指的是自定义 AuthenticationHandler bean,
<form-login login-page="/login.xhtml" authentication-success-handler-ref="customAuthenticationHandler"/>
...
</http>
<beans:bean id="customAuthenticationHandler" class="com.examples.CustomAuthenticationHandler" />
自定义 AuthenticationHandler 类如下所示:
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;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)