从授权服务器重定向后如何解决CORS错误?

我提出了一个 GET 请求https://auth.pingone.com/xxxxxxxxxxxxx/as/authorize/?response_type=code&client_id=xxxxxxxxxxxxxredirect_uri=http:%2F%2Flocalhost:3000%2F&scope=openid+profile&acr_values=Single_Factor,成功时返回一个Location带有302http 状态代码的标头。然后我的客户端(React.js SPA 应用程序)重定向到该位置。一切正常,直到 GET 请求,但当客户端尝试重定向到该位置时,出现 CORS 错误。

Access to XMLHttpRequest at 'http://localhost:3000/auth/login?environmentId=xxxxxxxxxxxxx&flowId=xxxxxxxxxxxxx' (redirected from 'https://auth.pingone.com/xxxxxxxxxxxxx/as/authorize/?response_type=code&client_id=xxxxxxxxxxxxxredirect_uri=http:%2F%2Flocalhost:3000%2F&scope=openid+profile&acr_values=Single_Factor') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我之前已经解决了 CORS,但这些请求是由我自己的服务器提供的,而不是 pingone.com。
我尝试在第一个 GET 请求中传递以下标头,但是在预检请求期间,即使是第一个 GET 请求也失败了。

"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": ["GET", "POST", "OPTIONS", "HEAD"],
"Access-Control-Allow-Headers": ["Origin", "Content-Type", "Accept", "X-Requested-With", "Access-Control-Allow-Methods"]

ping.com 授权服务器设置的响应头为:

access-control-allow-credentials: true
access-control-allow-headers: Origin,Content-Type,Content-Length,Content-Disposition,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,Cookie,Accept
access-control-allow-methods: OPTIONS,GET,POST
access-control-allow-origin: http://localhost:3000
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-length: 0
content-type: application/json
correlation-id: xxxxxxxxxxxxx
date: Mon, 01 Mar 2021 03:44:19 GMT
expires: 0
location: http://localhost:3000/auth/login?environmentId=xxxxxxxxxxxxx&flowId=xxxxxxxxxxxxx
pragma: no-cache
via: 1.1 01583e0e72b60e3d0d303e6b00e52b4d.cloudfront.net (CloudFront)
x-amz-apigw-id: xxxxxxxxxxxxx
x-amz-cf-id: xxxxxxxxxxxxx
x-amz-cf-pop: DEL51-C1
x-amzn-remapped-content-length: 0
x-amzn-requestid: xxxxxxxxxxxxx
x-amzn-trace-id: Root=1-603c6313-16fbca26388a6f732bb098e9;Sampled=0
x-cache: Miss from cloudfront

我在这里做什么以及可能的解决方案是什么?

回答

从您的评论中我看到,主要问题是对localhost含义的误解。http://localhost:3000-是一个服务器。它是 React 的开发服务器,用于托管您的页面。停止 React,您将在浏览器中在此地址上看不到任何内容。本地文件是在file://协议的帮助下提供的,而不是通过http://localhosthttp://显然存在服务器)

此阅读https://create-react-app.dev/docs/proxying-api-requests-in-development/可能会有所帮助

要告诉开发服务器将任何未知请求代理到开发中的 API 服务器,请向您的 API 服务器添加一个proxy字段package.json

方便地,这避免了 CORS 问题

您的问题还有其他解决方案,但这可能是文档中最强大和推荐的


以上是从授权服务器重定向后如何解决CORS错误?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>