java - 在 spring security 中禁用浏览器身份验证对话框

标签 java spring spring-mvc spring-security

我正在使用 spring security 4,出于某种原因,在我完成登录页面的身份验证后,我得到了浏览器身份验证对话框,这迫使我再次进行身份验证。

这是我的安全配置:

    http.antMatcher("/test")
            .httpBasic()
            .and()
            .authorizeRequests()
            .antMatchers("/index.html", "/login.html", "/", "/scripts/**",
                    "/bower_components/**", "/styles/**", "/views/**",
                    "/login", "/api/user/*").permitAll().anyRequest()
            .authenticated().and().logout().logoutUrl("/api/logout").and()
            .csrf().csrfTokenRepository(csrfTokenRepository()).and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);

最佳答案

身份验证弹出窗口是由响应头 WWW-Authenticate: Basic 引起的,它由 BasicAuthenticationEntryPoint 设置.

使用未设置 WWW-Authenticate: Basic 的自定义 AuthenticationEntryPoint:

public class NoPopupBasicAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
    }

}

将自定义身份验证入口点添加到安全配置(顺序很重要):

http
    .httpBasic()
    .authenticationEntryPoint(new NoPopupBasicAuthenticationEntryPoint())

关于java - 在 spring security 中禁用浏览器身份验证对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31424196/

相关文章:

java - java.lang.IllegalArgumentException : Not a managed type 的问题

java - 使用 Spring 获取 RESTful Web 服务来理解 JSON 字符串

mysql - 如何为具有大量表的 MySQL 数据库编写 Java Spring MVC 数据库访问类?

java - Spring MVC动态列表表单提交

java - 使用 FatJar 作为 native 库

java - ScheduledExecutor服务复用

java - 与线程的可变干扰

java - 如何查找当前正在监听 Activity 端口的进程(使用Java)

java - 使用 JPA 通过一列连接并返回另一列

java - 无法使用上下文 :property-placeholder (Spring) 获取属性