从 angular 发送不记名令牌时出现 CORS 问题

CORS problem when sending Bearer token from angular

问题是在向本地主机发送 GET 请求时未发送授权 header。 预检请求 ( OPTIONS ) 不包含授权 header 和 returns 401 状态。 我正在使用 Angular 拦截器将 header 添加到我的请求中,并 Spring 作为后端服务器启动。 这是发送 GET 请求时 Developer Firefox 中的控制台。 enter image description here

您的 CORS 过滤器:

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;
import java.util.List;    

@Component
public class CorsFilterConfig {

    public static final List<String> allowedOrigins = Arrays.asList("*");

    @Bean
    public FilterRegistrationBean<CorsFilter> initCorsFilter() {
        // @formatter:off
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
        config.addAllowedMethod("*");
        config.setAllowedOrigins(allowedOrigins);
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
        // @formatter:on
    }
}

拦截器位于 Angular:

    import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,

  HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { AppService } from '../services/app.service';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';
import { tap } from 'rxjs/operators';
import { ProgressBarService } from '../services/progress-bar.service';

@Injectable()
export class HttpTokenInterceptor implements HttpInterceptor {
  constructor(private app: AppService, private router: Router,
              private progressService: ProgressBarService) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const url = environment.api_url;
    if (req.url.indexOf('/oauth/') === -1) {  
      const token = this.app.getToken();
      const contentType = req.url.indexOf('/fileupload') >= 0  ? 'multipart/form-data' : 'application/json; charset=utf-8';
      let changeReg = req.clone({
        url: url + req.url,
        headers: req.headers
          .set('Content-Type', 'application/json; charset=utf-8')
          .set('Accept', 'application/json; charset=utf-8')
          .set('Authorization', token)
      });
      if (req.url.indexOf('/upload') >= 0 || req.url.indexOf('/fileupload') >= 0) {
        changeReg = req.clone({
          url: url + req.url,
          headers: req.headers
            .set('Authorization', token)
        });
      }
      this.progressService.show();
      return next.handle(changeReg).pipe(
        tap((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
            this.progressService.hide();
          }
        }, (error) => {
          this.progressService.hide();
        })
      );
    } else {
      this.progressService.show();
      const changeReg = req.clone({ url: url + req.url});
      return next.handle(changeReg).pipe(
        tap((event: HttpEvent<any>) => {
          if (event instanceof HttpResponse) {
            this.progressService.hide();
          }
        }, (error) => {
          this.progressService.hide();
        })
      );
    }
  }
}

只要删除对你来说多余的东西,祝你好运。