![](/img/trans.png)
[英]Redirect to different page after login based on user role with Spring Security
[英]spring security redirect based on role not working
好吧,我嘗試根據角色重定向用戶,但是我的自定義類什么也沒做,我沒有做一些系統,但是什么也沒發生。
我遵循這個小教程http://oajamfibia.wordpress.com/2011/07/07/role-based-login-redirect/#comment-12
但是我將自己的擴展類更改為SavedRequestAwareAuthenticationSuccessHandler,我也嘗試了本教程中的擴展類,但沒有任何反應,不知道我缺少什么。 任何幫助將不勝感激。
這是我的課
@Component
public class RoleBaseAuthentification extends SavedRequestAwareAuthenticationSuccessHandler{
private Map<String, String> roleMap;
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws ServletException, IOException {
System.out.println(request.getUserPrincipal());
if(authentication.getPrincipal() instanceof UserDetails){
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
System.out.println(userDetails);
String role = userDetails.getAuthorities().isEmpty() ? null : userDetails.getAuthorities().toArray()[0].toString();
System.out.println(role);
response.sendRedirect(request.getContextPath() + roleMap.get(role));
}
super.onAuthenticationSuccess(request, response, authentication);
}
public Map<String, String> getRoleMap() {
return roleMap;
}
public void setRoleMap(Map<String, String> roleMap) {
this.roleMap = roleMap;
}
}
這是我的security-context.xml
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,password,enabled from users where username = ?"
authorities-by-username-query="select u.username, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.username = ?" />
</security:authentication-provider>
</security:authentication-manager>
<security:http use-expressions="true">
<security:intercept-url pattern="/management" access="hasRole('ROLE_ADMIN')"/>
<security:form-login login-page="/login" authentication-success-handler-ref="redirectByRole"/>
</security:http>
<bean id="redirectByRole" class="com.freelogic.spring.web.service.RoleBaseAuthentification">
<property name="roleMap">
<map>
<entry key="ROLE_ADMIN" value="/management.jsp" />
<entry key="ROLE_USER" value="/home.jsp" />
</map>
</property>
</bean>
您的成功處理程序擴展了SavedRequestAwareAuthenticationSuccessHandler
因此調用
super.onAuthenticationSuccess(request, response, authentication)
導致SavedRequestAwareAuthenticationSuccessHandler
或其上級類之一使用其重定向策略並覆蓋您的重定向策略。
你可以通過調用避免重定向super.onAuthenticationSuccess()
的前reponse.sendRedirect()
它將覆蓋先前進行的重定向嘗試。 雖然不是一個好的解決方案,但是它將起作用。 見下文,為什么我認為這不是一個好的解決方案。
我不確定為什么要擴展SavedRequestAwareAuthenticationSuccessHandler
而不是簡單地實現AuthenticationSuccessHandler。 前者允許經過身份驗證的用戶重定向到其先前訪問的頁面。 您的RoleBaseAuthentification
僅按角色重定向,沒有條件返回到先前的URL。 因此,您選擇擴展SavedRequestAwareAuthenticationSuccessHandler
對我來說沒有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.