Spring Security:登录后如何重定向到REST URL

时间:2016-03-10 03:15:34

标签: java spring rest spring-mvc spring-security

我不确定我是否能够很好地了解主题,以正确地提出问题。

无论如何,登录后,我想重定向到url路径中用户名的url。我怎么能这样做?

例如,某人使用用户名“bmarkham”登录。我想在登录www.website.com/bmarkham后重定向

这是我的textarea

spring-security.xml

我已经尝试弄乱<form-login login-page="/login" default-target-url="/welcome/" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password" login-processing-url="/auth/login_check" /> 并且没有任何效果。

这是我的控制器

default-target-url

1 个答案:

答案 0 :(得分:4)

创建AuthenticationSuccessHandler的自定义实现:

package com.myapp.security;

public class RedirectLoginSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, 
            HttpServletResponse httpServletResponse, 
            Authentication authentication) throws IOException, ServletException {

        RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
        redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, 
            "www.website.com/"+authentication.getName());
    }
}

创建此处理程序的bean:

<bean id="successLoginHandler" class="com.myapp.security.RedirectLoginSuccessHandler" />

在安全配置中注册此bean:

<form-login login-page="/login" default-target-url="/welcome/"
        authentication-failure-url="/login?error" username-parameter="username"
        password-parameter="password" login-processing-url="/auth/login_check" 
        authentication-success-handler-ref="successLoginHandler"
/>

现在,您将在登录后重定向。

注意:如果您想重定向到控制器方法,只需重定向到映射网址即可。例如,对于重定向到"/welcome/{userName}",处理程序中的代码将如下所示:

@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, 
        HttpServletResponse httpServletResponse, 
        Authentication authentication) throws IOException, ServletException {

    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    redirectStrategy.sendRedirect(httpServletRequest, httpServletResponse, 
    "/welcome/"+authentication.getName());
}