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



我目前正在为一个学校项目创建一个简单的应用程序,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应用程序的响应包含以下标题,则它不是"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响应,您必须由您的angular应用程序(例如拦截器)处理该响应。

如果你需要一个如何做到这一点的例子,你可以看看我的购物清单应用程序。它采用了弹簧靴和棱角分明的js。

正如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中处理标头。

如上所述,问题出现在用值"WWW-Authenticate:Basic"设置的响应标头中。

另一个可以解决这个问题的解决方案是实现AuthenticationEntryPoint接口(直接),而不将这些值放在头中

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//(....)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/*.css","/*.js","/*.jsp").permitAll()
.antMatchers("/app/**").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/j_spring_security_check")
.defaultSuccessUrl("/", true)
.failureUrl("/login?error=true")
.usernameParameter("username")
.passwordParameter("password")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.logoutSuccessUrl("/login")
.deleteCookies("JSESSIONID")
.clearAuthentication(true)
.invalidateHttpSession(true)
.and()
.exceptionHandling()
.accessDeniedPage("/view/error/forbidden.jsp")
.and()
.httpBasic()
.authenticationEntryPoint(new AuthenticationEntryPoint(){ //<< implementing this interface
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
//>>> response.addHeader("WWW-Authenticate", "Basic realm="" + realmName + """); <<< (((REMOVED)))
response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
}
});
}
//(....)
}

最新更新