Spring Security条件default-target-url

时间:2012-08-13 08:55:39

标签: java spring spring-security

我注意到有几个问题询问这个话题。我查看了它们,我无法将它们应用到我特定的Spring设置中。我想根据用户的角色将我的登录重定向配置为有条件的。这就是我到目前为止所做的:

<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

<bean id="authenticationProcessingFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler" ref="authenticationSuccessHandler"/>
</bean>
<bean id="authenticationSuccessHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler">
    <property name="defaultTargetUrl" value="/login.jsp"/>
</bean>

编辑2

目前我没有像this example所示的public class Test implements AuthenticationSuccessHandler {}类。

2 个答案:

答案 0 :(得分:21)

我测试了代码并且它有效,其中没有火箭科学

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");
    }    
}

安全上下文的变化:

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

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

更新如果您想使用default-target-url方法,它会同样有效,但会在您的用户首次访问登录页面时触发:

<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");
    }
}

答案 1 :(得分:0)

IMO的一种更合适的方法是创建一个扩展SimpleUrlAuthenticationSuccessHandler的类,然后覆盖其determineTargetUrl方法。来自the docs

根据主类Javadoc中定义的逻辑来构建目标URL。

...听起来有些混乱,但基本上,您可以编写确定目标URL所需的任何逻辑,然后将其作为字符串返回。