Angular2 身份验证失败,返回 401

Angular2 authentication fail with 401

我正在使用 Spring-MVC 构建 Angular2 应用程序。我使用 Spring 安全性添加了身份验证,当我使用邮递员查询我的 REST 服务器时,一切都很好。当我在 Angular2 中将 Authorization 添加到我的 header 时,出现 401 错误。

错误: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 401

我的 Angular2 服务:

@Injectable()
export class BookService {
  headers = new Headers();
  options = new RequestOptions({ headers: this.headers });

  constructor(
    private http: Http) {
      this.headers.append('Content-Type', 'application/json');
      this.headers.append('Authorization', 'Basic ' + btoa('nirgn:password'));
  }

  getBooksByCategory(categoryId: number) {
    return this.http.get(environment.baseUrl + 'categories/' + categoryId + '/books', this.options)
      .map((res: Response) => <Book[]>res.json()._embedded.books)
      .catch(this.handleError);
  }
}

在 spring 中,我允许这样的所有来源:response.addHeader("Access-Control-Allow-Origin", "*");(在 CORSFilter implements Filter class 中)。

此外,我添加了这样的身份验证:

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

当我删除 .and().authorizeRequests().anyRequest().authenticated() 时,我没有收到任何错误,并且能够 GET 来自服务器的数据。

所以,总而言之,我很确定这不是 Access-Control-Allow-Origin,这是因为服务器没有获得我的授权 header。当我尝试在邮递员中查询服务器时,如果没有身份验证,我也会得到 401,但是当我添加基本身份验证时,我会得到 200。

我还检查了 postman 和 angualr2 中的密码输出,以确保 angualr2 中的 'Basic ' + btoa('nirgn:password') 输出的密码与 postman 输出的密码相同,而且是相同的。这里是:

所以我设法弄明白了。毕竟是 CORS(在 spring 中)。

我不得不告诉我的 configure class 使用我创建的 CORSFilter

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and().authorizeRequests().anyRequest().authenticated()
        .and().addFilterAfter(new CORSFilter(), CsrfFilter.class);
}

奇怪的是,我仍然不明白为什么邮递员成功了,而在浏览器中(angular)却出现错误。