分享

春季-身份验证失败重定向,请求参数不起作用

 印度阿三17 2019-10-11

我正在尝试配置自己的成功和身份验证失败处理程序.在身份验证失败时,我想使用请求参数重定向回我的登录页面,此参数的存在将在我的登录页面上输出错误消息.但是,尽管发生错误,但我却被重定向回我的登录页面,但request参数始终为null.

代码如下:

protected void configure(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login.html").permitAll() 
            .usernameParameter("username")
            .passwordParameter("password")                                               
            .loginProcessingUrl("/login")
            .successHandler(successHandler())
            .failureHandler(handleAuthenticationFailure());
}

@Autowired
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //database checks
}
};
}

/**
 * Authentication success handler defines action when successfully authenticated
 * @return
 */
@Bean
public AuthenticationSuccessHandler successHandler(){
    return new AuthenticationSuccessHandler() {

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

            // custom auth success here
            httpResponse.setStatus(HttpServletResponse.SC_OK);
            SavedRequest savedRequest = (SavedRequest) httpRequest.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST");
            httpResponse.sendRedirect(savedRequest.getRedirectUrl());
        }
    };
}

@Bean
public AuthenticationFailureHandler handleAuthenticationFailure() {
    return new SimpleUrlAuthenticationFailureHandler() {

        @Override
        public void onAuthenticationFailure(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
                                            AuthenticationException authenticationException) throws IOException, ServletException {

            // custom failure code here
            setDefaultFailureUrl("/login.html?error=fail");
            super.onAuthenticationFailure(httpRequest, httpResponse, authenticationException);
        }
    };
}

解决方法:

试试这个:

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

    // .......

    response.sendRedirect("/login.html?error=fail");    
}

更新:

将“ /login.html?error=fail”添加到authorizeRequests()部分非常重要,否则控制器将不会选择error参数.

将.antMatchers(“ / login”).permitAll()替换为.antMatchers(“ / login **”).permitAll()

来源:https://www./content-4-502701.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多