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

时间:2016-06-11 11:26:15

标签: java angularjs spring-security spring-boot http-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';
  }
]);

3 个答案:

答案 0 :(得分:20)

让我们从您的问题开始

如果Spring Boot应用程序的响应包含以下标题,那么它不是一个“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应用程序的响应包含标题WWW-Authenticate: Basic,则会显示弹出窗口。不应对Spring Boot应用程序中的所有请求禁用此功能,因为它允许您非常轻松地浏览浏览器中的api。

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

X-Requested-With: XMLHttpRequest

如何将此标头添加到AngularJS应用程序发出的每个请求

您可以在应用配置中添加默认标头,如:

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

后端现在会响应你的角度应用程序(例如拦截器)必须处理的401响应。

如果您需要一个示例,请查看我的shopping list app。它完成了弹簧靴和角度js。

答案 1 :(得分:3)

正如Yannic Klem所说的,这是因为标题引起的

WWW-Authenticate: Basic

但是在春季,有一种方法可以将其关闭,这确实很简单。在您的配置中,只需添加:

.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)

,由于尚未定义 authenticationEntryPoint ,因此请在开始时自动进行接线:

@Autowired private MyBasicAuthenticationEntryPoint authenticationEntryPoint;

现在创建 MyBasicAuthenticationEntryPoint.class 并粘贴以下代码:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;

@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {

/**
 * Used to make customizable error messages and codes when login fails
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx) 
  throws IOException, ServletException {
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    PrintWriter writer = response.getWriter();
    writer.println("HTTP Status 401 - " + authEx.getMessage());
}

@Override
public void afterPropertiesSet() throws Exception {
    setRealmName("YOUR REALM");
    super.afterPropertiesSet();
}
}

现在您的应用程序将不再发送 WWW-Authenticate:Basic 标头,因为将不会显示弹出窗口,并且无需弄乱Angular中的标头。

答案 2 :(得分:2)

如上所述,问题出在响应标头中,该标头设置为“ WWW-Authenticate:Basic”。

可以解决此问题的另一种解决方案是直接实现AuthenticationEntryPoint接口,而无需将这些值放在标题中

CMake Error: CMake was unable to find a build program corresponding to "MinGW Makefiles".  CMAKE_MAKE_PROGRAM is not set.  You probably need to select a different build tool.
CMake Error: CMake was unable to find a build program corresponding to "MinGW Makefiles".  CMAKE_MAKE_PROGRAM is not set.  You probably need to select a different build tool.
CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage
CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage