Spring Security 条件 default-target-url

2022-09-04 01:35:48

我注意到有几个问题询问这个话题。我查看了它们,我无法将它们应用于我特定的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>

我认为这个问题可能与我试图做的事情是一致的。有谁知道我该如何应用它?

编辑 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

目前,我没有此示例中所示的类。public class Test implements AuthenticationSuccessHandler {}


答案 1

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

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

答案 2

IMO 更合适的方法是创建一个扩展的类,然后重写它的方法。从文档中SimpleUrlAuthenticationSuccessHandlerdetermineTargetUrl

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

...这听起来有点令人困惑,但基本上你写了确定目标URL所需的任何逻辑,然后只需将其作为字符串返回即可。


推荐