通过Angular 5和Spring Sec 5中的HTTP GET请求对用户进行身份验证

时间:2018-07-16 12:35:00

标签: spring angular spring-security http-headers basic-authentication

我正在从事Spring Boot 2 + Angular 5项目。对于那些想重新认识它的人来说,这是从Spring Guides网站上的Spring Security and Angular tutorial中学到的。

我有一个使用基本身份验证的安全后端。

@SpringBootApplication
@RestController
public class BasicApplication extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {
    public static void main(String[] args) {
        SpringApplication.run(BasicApplication.class, args);
    }

    @GetMapping("/resource")
    public Map<String, Object> home() {
        Map<String, Object> model = new HashMap<>();
        model.put("id", UUID.randomUUID().toString());
        model.put("content", "Hello Spring Security Boot 2 and Angular");
        return model;
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/resource")
                .allowedOrigins("http://localhost:4200")
                .allowedMethods("GET");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }
}

卷曲/resource端点时,我成功

curl http://user:password@localhost:8080/resource

我想对Angular执行完全相同的身份验证之王。因此,我实现了以下组件:

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Hello WAT';
  greeting = { id: 'XXX', content: 'Hello World' };

  constructor(private http: HttpClient) {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'user:password'
      })
    };

    http
      .get<any>('http://localhost:8080/resource', httpOptions)
      .subscribe(resource => (this.greeting = resource));
  }
}

这是浏览器日志中的内容:

Access-Control-Request-Headers authorization,content-type

从逻辑上讲,这是Spring Sec DEBUG日志所说的:

2018-07-16 14:25:28.355 DEBUG 8792 --- [nio-8080-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9a00c039: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
...
2018-07-16 14:25:28.377 DEBUG 8792 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.

1 个答案:

答案 0 :(得分:0)

首先,我必须感谢user184994的有用评论:添加'Basic ' + btoa(...)确实有用!

'Authorization': 'Basic ' + btoa('user:password')

接下来,在使用各种浏览器进行测试之后,我最终偶然发现了以下错误消息:

Failed to load http://localhost:8080/resource: Response for preflight has invalid HTTP status code 401.

经过一番研究和反复无常的研究,我发现在Spring Security中添加CORS配置确实可以解决问题。

http
     ...
     .and()
     .cors()