【发布时间】:2019-12-11 20:53:40
【问题描述】:
我使用 .NET Core 2.2 创建了一个 API,后来部署在 Azure API 管理服务中。然后我将 API 配置为仅对有效的访问令牌执行。我也在这个配置中启用了 cors:
<policies>
<inbound>
<validate-jwt header-name="Authorization" failed-validation-httpcode="401" failed-validation-error-message="Unauthorized. Access token is missing or invalid.">
<openid-config url="https://myTenant.b2clogin.com/myTenant.onmicrosoft.com/v2.0/.well-known/openid-configuration?p=B2C_1_react_signup" />
<audiences>
<audience>APP-Id-999999999999999999999</audience>
</audiences>
<issuers>
<issuer>https://myTenant.b2clogin.com/xxxxxxxxxxxxxxxxxxxxxx/v2.0/</issuer>
</issuers>
</validate-jwt>
<base />
<set-backend-service id="apim-generated-policy" backend-id="webAPI" />
<cors>
<allowed-origins>
<origin>http://localhost:3000</origin>
</allowed-origins>
<allowed-methods>
<method>GET</method>
<method>POST</method>
</allowed-methods>
</cors>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
在前端,我有一个使用 React 和 Express 运行的 Web 应用程序。该应用程序在我的本地服务器中运行:http://localhost:3000
当我执行我的 Azure 策略(用户流)“B2C_1_react_signup”进行登录时,我会获得一个有效的访问令牌,并且我可以从邮递员那里执行 API,并将标题放入:授权作为密钥,访问令牌作为价值。这在没有任何 CORS 问题的情况下有效。
当我尝试从页面执行相同操作时,身份验证转到 Azure B2C 网站,如果身份验证成功,它将重定向到我的页面 (http://localhost:3000),我在浏览器的 localStorage 中看到 access_token 和 id_token .
这是我从控制台得到的错误:
CORS 策略已阻止从源“http://localhost:3000”获取“https://myAPI.azure-api.net/api/private”的访问权限:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源上。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
这是我的反应代码:
import React, { Component } from "react";
import Auth from "./Auth/Auth";
class Private extends Component {
constructor(props) {
super(props);
this.auth = new Auth();
}
state = {
message: ""
};
componentDidMount() {
this.idToken = this.auth.getTokens().idToken;
console.log("");
console.log("ID TOKEN: " + this.idToken);
console.log("");
fetch("https://myAPI.azure-api.net/api/private", {
headers: { Authorization: `${this.idToken}` }
})
.then(response => {
if (response.ok) return response.json();
throw new Error("Network response was not ok.");
})
.then(response => this.setState({ message: response }))
.catch(error => this.setState({ message: error.message }));
}
render() {
return <p>{this.state.message}</p>;
}
}
export default Private;
注意这一行的Id_token是正确的:
headers: { Authorization: `${this.idToken}` }
如果我将它复制并粘贴到邮递员中,没有 Bearer 它就可以工作。
关于如何解决这个问题的任何建议?我是否应该修改我的 .NET Web API 并在其中启用 CORS,然后再次在 azure 中部署?为什么 Azure 中的 CORS 策略不起作用?
谢谢
【问题讨论】:
-
嗨@MarcosF8,怎么样?这个问题解决了吗?
标签: reactjs azure cors asp.net-core-webapi azure-ad-b2c