簡體   English   中英

Spring安全未按預期重定向

[英]Spring security is not redirecting as expected

我正在實施春季安全措施。 登錄正常,但未按預期重定向

這是我的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:

調試器截圖

但是在我的應用程序中,我被重定向到我確實用於記錄的網址:

CustomAuthenticationSuccessHandler之后的URL

希望任何人能幫助我! 問候,

您需要添加: 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"/>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM