被 CORS 策略阻止 - 通配符“*”且 withCredentials 为 true

问题描述 投票:0回答:1

我收到以下 CORS 错误:

 Access to XMLHttpRequest at 'https://my.domain/api/chat/info?t=1701325904808' from 
 origin 'http://localhost:8100' has been blocked by CORS policy: The value of the 
 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when 
 the request's credentials mode is 'include'. The credentials mode of requests 
 initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
 chatItemMessage.page.ts:40     GET https://my.domain/api/chat/info?t=1701325904808 
 net::ERR_FAILED 200 (OK)

客户有办法解决这个问题吗? 我使用这两个包是因为后端也使用SockJS(Spring Boot):

npm install sockjs-client
npm install stompjs

我有这个AppHttpInterceptor:

@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {

constructor(protected authService: AuthService, private router: Router) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.authService.getToken()).pipe(
        switchMap((token) => {
            const tokenString: string = token as string;
            if(token) {
                let authReq = req.clone({
                    setHeaders: {  
                        'x-auth-token': tokenString,
                        'Content-Type': 'application/json'
                        }
                });
                return next.handle(authReq);
            } else {
                return next.handle(req);
            } 
        })
    );
  }
}  

但是如果请求 GET https://my.domain/api/chat/info?t=1701325904808,则永远不会调用此拦截器。 我已经阅读了几乎所有有关异常的内容,但我不知道该怎么做才能解决这个问题。

这是我的 webSocked 代码:

const socket = new SockJS('https://my.domain/api/chat');
const stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
    alert('connected StompClient in chatItemMessage.page.ts');    
});
angular ionic-framework cors stomp sockjs
1个回答
0
投票

不行,这个需要在服务器端解决。服务器不得使用通配符,而是返回“Access-Control-Allow-Origin”中允许的特定来源(或来源列表)。

您可以在后端执行的操作是始终在“Access-Control-Allow-Origin”中返回请求的来源,以允许任何具有凭据的来源(但考虑到安全隐患,固定列表始终是更好的选择)。这实际上是一个通配符,但不受此限制。

© www.soinside.com 2019 - 2024. All rights reserved.