Spring authenticationEntryPoint 不会显示默认的 Spring Session 默认表单(404 错误)

时间:2021-02-04 18:55:52

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

我有一个 Spting 启动应用程序 2.4.2。我设置了 java 安全登录表单,没有任何问题。

现在我想让我的 AJAX 请求在会话丢失时得到错误而不是重定向。

我向 WebSecurityConfigurerAdapter 添加了一个 authenticationEntryPoint 并且似乎按预期工作。问题是我无法再显示默认的登录和注销表单。我收到 404 错误。

我的安全配置


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    private MyLogoutSuccessHandler myLogoutSuccessHandler;
        
    protected void configure(final HttpSecurity http) throws Exception {
        
        http.authorizeRequests()
        .antMatchers("/login**").permitAll()
        .antMatchers("/api/**").permitAll()
        .antMatchers("/css/**").permitAll()
        .anyRequest().authenticated()
        
        .and().formLogin().defaultSuccessUrl("/checador")
        .and().logout().logoutSuccessHandler(myLogoutSuccessHandler)
        .and() 
            .exceptionHandling().
             authenticationEntryPoint(new AjaxAwareAuthenticationEntryPoint("/login"))
        ;
        
           
           
    }

这是我的 LoginUrlAuthenticationEntryPoint 类

@Slf4j
public class AjaxAwareAuthenticationEntryPoint extends LoginUrlAuthenticationEntryPoint     
{
  
    public AjaxAwareAuthenticationEntryPoint(String loginFormUrl) {
        super(loginFormUrl);
    }

    
    public void commence(
        HttpServletRequest request,
        HttpServletResponse response,
        AuthenticationException authException)
        throws IOException, ServletException {
        String ajaxHeader = ((HttpServletRequest) request).getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest".equals(ajaxHeader);
        if (isAjax) {           
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Ajax REquest Denied (Session Expired)");
        } else {
            super.commence(request, response, authException);
       }
    }
}

这样我得到一个“出现意外错误(类型=未找到,状态=404)”。如果我评论 authenticationEntryPoint,我将看到我的默认 Java 安全会话登录表单。

如何启用它?

谢谢

0 个答案:

没有答案
相关问题