首页 > 解决方案 > 如何在 Spring Security 中启用基本授权?

问题描述

我想用 Spring Security 和 Angular 编写一个应用程序,注册后的用户可以在其中登录。我已经创建了允许用户注册的功能,但是在登录时我遇到了问题。我正在使用基本身份验证方法,它发送到达服务器的相关凭据并执行身份验证(安全日志将在下面)但是即使身份验证成功,也会有 HttpErrorResponse。与我所拥有的相关的代码如下。

登录端点:

@GetMapping("/users")
public Principal user(Principal user) {
    return user;
}

登录请求:

public authenticate(username: string, password: string, callback) {

const headers = new HttpHeaders({
  authorization: 'Basic ' + btoa(username + ':' + password)
});

this.httpClient.get('http://localhost:8080/users', { headers: headers }).subscribe(response => {
  if (response['name']) {
    this.authenticated = true;
    console.log(response);
  } else {
    this.authenticated = false;
    console.log(response);
  }
  return callback && callback();
});

}

注册端点:

@PostMapping("/users")
ResponseEntity<String> registerUser(@RequestBody String json) {
    JSONObject user = new JSONObject(json);
    return responseGenrator.generateRegistrationResponse(userRegistrator.registerUser(user));
}

申请注册:

public registerUser(username: string, email: string, password: string) {
this.httpClient.post('http://localhost:8080/users',
  {
    "username": username,
    "email": email,
    "password": password
  }, { responseType: 'text', observe: 'response' })
  .subscribe(response => {
    this.responseStatus = response.status;
  }, error => {
    this.httpErrorResponse = error;
    this.responseStatus = this.httpErrorResponse.status;
  });

}

安全配置:

@Configuration
@Order(SecurityProperties.BASIC_AUTH_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity httpSecurity) {
    try {
        httpSecurity.httpBasic();
        httpSecurity.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated();
        httpSecurity.authorizeRequests().antMatchers("/users", "/login", "/user").permitAll().anyRequest()
                .anonymous();
        httpSecurity.csrf().disable();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

安全相关过滤:

@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
    final FilterChain filterChain) throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
    response.addHeader("Access-Control-Allow-Headers",
            "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
    response.addHeader("Access-Control-Expose-Headers",
            "Access-Control-Allow-Origin, Access-Control-Allow-Credentials");
    response.addHeader("Access-Control-Allow-Credentials", "true");
    response.addIntHeader("Access-Control-Max-Age", 10);
    filterChain.doFilter(request, response);
}

相关安全日志:

2019-04-10 16:14:54.721 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/users'; against '/'
2019-04-10 16:14:54.721 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /users; Attributes: [anonymous]
2019-04-10 16:14:54.721 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@9f9c73e6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2019-04-10 16:14:54.722 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@2bc279a5, returned: 1
2019-04-10 16:14:54.722 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2019-04-10 16:14:54.722 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2019-04-10 16:14:54.722 DEBUG 16708 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /users reached end of additional filter chain; proceeding with original chain
2019-04-10 16:14:54.724 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2019-04-10 16:14:54.724 DEBUG 16708 --- [nio-8080-exec-5] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@376adbc7
2019-04-10 16:14:54.724 DEBUG 16708 --- [nio-8080-exec-5] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2019-04-10 16:14:54.724 DEBUG 16708 --- [nio-8080-exec-5] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

相关控制台日志文本:

Access to XMLHttpRequest at 'http://localhost:8080/users' from origin 'http://localhost:4200' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

标签: javaangularspring-security

解决方案


推荐阅读