2012-08-13 133 views
12

我注意到有几个问题关于这个话题。我翻看了他们,我无法将它们应用到我的特定的Spring设置。我想根据用户的角色将我的登录重定向配置为有条件的。这是我到目前为止有:Spring Security条件default-target-url

<http auto-config="true" use-expressions="true"> 
     <custom-filter ref="filterSecurityInterceptor" before="FILTER_SECURITY_INTERCEPTOR"/> 
     <access-denied-handler ref="accessDeniedHandler"/> 
     <form-login 
      login-page="/login" 
      default-target-url="/admin/index" 
      authentication-failure-url="/index?error=true" 
      /> 
     <logout logout-success-url="/index" invalidate-session="true"/> 
</http> 

我想this question可能是在同一行什么,我试图做的。任何人都知道我可以如何应用它?

编辑1

​​

EDIT 2

目前我没有像public class Test implements AuthenticationSuccessHandler {}类如图this example

+3

你的问题是相同的[这一个](http://stackoverflow.com/questions/7470405/authenticationsuccesshandler-example-for-spring-security-3) – 2012-08-13 10:42:41

+0

谢谢。你可以检查**编辑1 **。我感到困惑,因为我已经为该bean分配了一个spring类? – ThreaT 2012-08-13 11:08:57

+0

还没有形成 - 登录authenticationSuccessHandler? http://static.springsource.org/spring-security/site/docs/3.0.x/reference/appendix-namespace.html – 2012-08-13 11:16:25

回答

20

我已经测试的代码和它的作品,有一个在它

public class MySuccessHandler implements AuthenticationSuccessHandler { 

    @Override 
    public void onAuthenticationSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication) 
      throws IOException, ServletException { 
     Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities()); 
     if (roles.contains("ROLE_ADMIN")){ 
      response.sendRedirect("/Admin.html"); 
      return; 
     } 
     response.sendRedirect("/User.html"); 
    }  
} 

发生在你的安全上下文中没有火箭科学:如果你想使用default-target-url方法

<bean id="mySuccessHandler" class="my.domain.MySuccessHandler"> 
    </bean> 

<security:form-login ... authentication-success-handler-ref="mySuccessHandler"/> 

更新,它将同样工作,但会在用户第一次访问登录页面时触发:

<security:form-login default-target-url="/welcome.htm" />

@Controller 
public class WelcomeController { 
    @RequestMapping(value = "/welcome.htm") 
    protected View welcome() { 

     Set<String> roles = AuthorityUtils 
       .authorityListToSet(SecurityContextHolder.getContext() 
         .getAuthentication().getAuthorities()); 
     if (roles.contains("ROLE_ADMIN")) { 
      return new RedirectView("Admin.htm"); 
     } 
     return new RedirectView("User.htm"); 
    } 
} 
+0

如果我想重定向到另一个域,该怎么办? @Boris Treukhov – Mahdi 2016-04-04 07:47:20

+1

如果有人使用Sprint上下文的Java代码:'formLogin()。successHandler(new MySuccessHandler())' – RAS 2017-07-05 10:23:20