【问题标题】:Ionic CORS Problem only if adding custom header to request (Spring boot backend)仅在将自定义标头添加到请求时出现离子 CORS 问题(Spring 引导后端)
【发布时间】:2020-07-03 03:33:33
【问题描述】:

我知道... CORS 问题是一个很好讨论的话题。在寻找了几个小时来解决我的问题之后,我现在向您寻求帮助:)

我的后端有一个 ionic angular 应用程序和一个 spring boot 应用程序。后端托管在公共服务器上(带有域)并使用letsencrypt ssl加密。

在我添加自定义标题之前,一切正常。对于每个请求,我都会收到一个 cors 错误:

Access to XMLHttpRequest at 'https://www.BACKEND_URL.com:5000/healthstatus' 
from origin 'http://localhost:8100' has been blocked by CORS policy: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

我已经使用这样的拦截器添加了自定义标头参数:

import {Injectable} from '@angular/core'; 
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import {Observable} from "rxjs"; 
import {AuthService} from "../services/auth.service";

@Injectable() export class TokenInterceptor implements HttpInterceptor {

  constructor(public auth: AuthService) { } 

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   console.log('####: interceptor: addHeader'); 
   request = request.clone({ setHeaders: { Authorization: `Bearer TEST-TOKEN` } });
   return next.handle(request);
  }
}

在控制器上我还添加了 CrossOrigin 注释

@CrossOrigin
@Controller

只有当我编辑标题时,我才会收到 CORS 错误。你能给我一个建议吗?还有其他方法可以将我的令牌添加到请求中吗?

提前致谢

【问题讨论】:

    标签: angular spring spring-boot ionic-framework cors


    【解决方案1】:

    我终于找到了解决办法!

    在 Spring Boot 中,我使用的是“HandlerInterceptor”。这个拦截器只允许请求头中有我的令牌。

    当浏览器向服务器询问某些 cors 信息时,浏览器会向后端服务器发送 OPTIONS-调用。此选项调用也被拒绝,因此无法检索允许的方法/标头/来源...

    我的代码是这样的

    if (request.getMethod().equals("OPTIONS")) { 
        response.setHeader("Access-Control-Allow-Origin", "*");
        //I've changed the 'Authorization' header to 'token' (at the end of the following codeline) 
        response.setHeader("Access-Control-Allow-Headers", "AuthID,Origin,X-Requested-With,Content-Type,Accept,token");
        //After that, continue without checking if the request is correct
        return true; 
    } else {
        //check if the request-header contains my token...
    }
    

    如果你已经实现了 spring boot 安全,你应该调整以下代码:

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/", "/**").permitAll()
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated();
    
            http.csrf().disable();
            http.headers().frameOptions().disable();
        }
    

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 2016-08-27
      • 2016-11-14
      • 1970-01-01
      • 2020-03-11
      • 2016-03-27
      • 2020-05-07
      • 2023-03-25
      • 2014-08-13
      相关资源
      最近更新 更多