java - Spring Boot 安全性在登录失败后显示 Http-Basic-Auth 弹出窗口

标签 java angularjs spring-security spring-boot basic-authentication

我目前正在为一个学校项目、Spring Boot 后端和 AngularJS 前端创建一个简单的应用程序,但有一个我似乎无法解决的安全问题。

登录工作完美,但当我输入错误的密码时,会出现默认登录弹出窗口,这有点烦人。我尝试了注释“BasicWebSecurity”并将 httpBassic 置于禁用状态,但没有结果(这意味着登录过程不再有效)。

我的安全等级:

package be.italent.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.csrf.CsrfFilter;
import org.springframework.security.web.csrf.CsrfToken;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.WebUtils;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    @Override
    public void configure(WebSecurity web){
        web.ignoring()
        .antMatchers("/scripts/**/*.{js,html}")
        .antMatchers("/views/about.html")
        .antMatchers("/views/detail.html")
        .antMatchers("/views/home.html")
        .antMatchers("/views/login.html")
        .antMatchers("/bower_components/**")
        .antMatchers("/resources/*.json");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic()
                    .and()
                .authorizeRequests()
                .antMatchers("/user", "/index.html", "/", "/projects/listHome", "/projects/{id}", "/categories", "/login").permitAll().anyRequest()
                .authenticated()
                    .and()
                .csrf().csrfTokenRepository(csrfTokenRepository())
                    .and()
                .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class).formLogin();
    }

    private Filter csrfHeaderFilter() {
        return new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain filterChain)
                    throws ServletException, IOException {
                CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
                        .getName());
                if (csrf != null) {
                    Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
                    String token = csrf.getToken();
                    if (cookie == null || token != null
                            && !token.equals(cookie.getValue())) {
                        cookie = new Cookie("XSRF-TOKEN", token);
                        cookie.setPath("/");
                        response.addCookie(cookie);
                    }
                }
                filterChain.doFilter(request, response);
            }
        };
    }

    private CsrfTokenRepository csrfTokenRepository() {
        HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
        repository.setHeaderName("X-XSRF-TOKEN");
        return repository;
    }
}

有没有人知道如何在不破坏其余部分的情况下防止显示此弹出窗口?

解决方案

将此添加到我的 Angular 配置中:

myAngularApp.config(['$httpProvider',
  function ($httpProvider) {
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  }
]);

最佳答案

让我们从您的问题开始

如果您的 Spring Boot 应用程序的响应包含以下 header ,则它不是“Spring Boot 安全弹出窗口”,而是显示的浏览器弹出窗口:

WWW-Authenticate: Basic

在您的安全配置中,出现了一个 .formLogin()。这不应该是必需的。虽然您想通过 AngularJS 应用程序中的表单进行身份验证,但您的前端是一个独立的 javascript 客户端,它应该使用 httpBasic 而不是表单登录。

您的安全配置会是什么样子

我删除了 .formLogin() :

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic()
                .and()
            .authorizeRequests()
            .antMatchers("/user", "/index.html", "/", "/projects/listHome", "/projects/{id}", "/categories", "/login").permitAll().anyRequest()
            .authenticated()
                .and()
            .csrf().csrfTokenRepository(csrfTokenRepository())
                .and()
            .addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}

如何处理浏览器弹窗

如前所述,如果您的 Spring Boot 应用程序的响应包含 header WWW-Authenticate: Basic,则会显示弹出窗口。不应为 Spring Boot 应用程序中的所有请求禁用此功能,因为它允许您非常轻松地在浏览器中探索 api。

Spring Security 有一个默认配置,允许您在每个请求中告诉 Spring Boot 应用程序不要在响应中添加此 header 。这是通过为您的请求设置以下 header 来完成的:

X-Requested-With: XMLHttpRequest

如何将此 header 添加到 AngularJS 应用发出的每个请求

您可以像这样在应用程序配置中添加一个默认 header :

yourAngularApp.config(['$httpProvider',
  function ($httpProvider) {
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
  }
]);

后端现在将响应 401 响应,您必须通过 Angular 应用程序(例如通过拦截器)处理该响应。

如果您需要如何执行此操作的示例,您可以查看我的 shopping list app .它是用 spring boot 和 angular js 完成的。

关于java - Spring Boot 安全性在登录失败后显示 Http-Basic-Auth 弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37763186/

相关文章:

java - 如何将 Map<Object, List<Object>> 传递给 Struts 2 中的操作

javascript - 以 Angular 动态添加到列表

javascript - 如何将一个 View 移动到具有不同路径文件的 Angular 另一个 View ?

java - 为什么大型 RSA key 不加密为唯一值?

java - 重新喷漆不起作用

java - 用图像网格填充屏幕的最佳方法

javascript - 使用 javascript 和 AngularJS 检测重写规则后面是否存在资源

java - 列表中的 Spring Security ACL

java - Spring Security 加密字符串 - Go 中解密失败

spring-security - 使用 Spring Security 时,oauth 范围和角色之间有什么区别吗?