Spring安全性未按预期重定向

时间:2017-06-27 01:53:04

标签: java spring-mvc spring-security

我正在实施spring-security。登录工作正常,但没有按预期重定向

这是我的JSP表单:

    <form id="login-form" name="loginForm">
        <div class="form-group">
            <label for="usrname" ><span class="glyphicon glyphicon-user"></span> Correo</label>
            <input type="text" class="form-control" name="correo" id="correo">
        </div>
        <div class="form-group">
            <label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Contraseña</label>
            <input type="password" class="form-control" name="password">
        </div>
        <div class="checkbox">
            <label><input type="checkbox" value="" checked>Remember me</label>
        </div>
        <div class="form-group">
            <button type="submit" id="loginBtn" class="btn btn-success btn-block"><span class="glyphicon glyphicon-off"></span> Iniciar sesion </button>
        </div>                                   
</form>

使用此JQuery Ajax调用调用此表单:

$.ajax({
            url: '/EProducts/j_spring_security_check',
            type: 'POST',
            data: form.serialize(),
            success: function(result){

               console.log(result.login);
               if(result.login == undefined){
                   self.submit();
               }else{
                   errorMsg.text(result.login.FAILURE).addClass("alert alert-danger");
                   agitar('#errorMsg');
               }

            },
            complete: function (e) {               
                form.data('requestRunning', false);
           }

        });

这是我的spring-security.xml:

    <http pattern="/resources/**" security="none" />
    <http auto-config="true" use-expressions="true"> 


            <form-login
                login-processing-url="/j_spring_security_check"
                authentication-success-handler-ref="customAuthenticationSuccessHandler"
                authentication-failure-handler-ref="customAuthenticationFailureHandler"
                username-parameter="correo"
                password-parameter="password"               
            />
            <csrf disabled="true"/>          
        </http>
    <authentication-manager>
      <authentication-provider ref="customAuthenticationProvider"/>
    </authentication-manager>

在spring-security xml中我正在使用customAuthenticationProvider:

public class CustomAuthenticationProvider implements AuthenticationProvider {

    private UserService userService = new UserService();

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = (String) authentication.getCredentials();

        User user = userService.loginUser(username, password);

        if (user == null) {
            throw new BadCredentialsException("Username not found.");
        }

        Collection<? extends GrantedAuthority> authorities = user.getAuthorities();

        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> arg0) {
        return true;
    }
}

这是我的CustomAuthenticationSuccessHandler,它返回评估用户角色的url值。

public class CustomAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        HttpSession session = request.getSession();

        User authUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        session.setAttribute("correo", authUser.getCorreo());
        session.setAttribute("authorities", authentication.getAuthorities());

        String targetUrl = determineTargetUrl(authentication);
        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        Set<String> authorities = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (authorities.contains("ROLE_ADMIN")) {
            return "/admin";
        } else if (authorities.contains("ROLE_USER")) {
            return "/EProducts/home";
        } else {
            throw new IllegalStateException();
        }
    }


    public RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }


public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
    this.redirectStrategy = redirectStrategy;
}

}

如果我用调试器检查值,我看到sucessHandler正在返回新的url:

Debugger Screenshot

但在我的应用程序中,我被重定向到我用来记录的URL:

URL after CustomAuthenticationSuccessHandler

希望有人能帮助我! 的问候,

1 个答案:

答案 0 :(得分:0)

您需要添加:default-target-url="/yourLandingPageHere.html"

default-target-url - 成功登录后的目标网页

像这样:

<form-login
default-target-url="/yourLandingPageHere.html"
            authentication-success-handler-ref="customAuthenticationSuccessHandler"
            authentication-failure-handler-ref="customAuthenticationFailureHandler"
            username-parameter="correo"
            password-parameter="password"/>