gpt4 book ai didi

c# - API 应用程序的 Azure 服务主体身份验证

转载 作者:行者123 更新时间:2023-12-02 08:06:22 25 4
gpt4 key购买 nike

我使用 REST 服务构建了一个简单的 API 应用程序。现在我已在 Azure 应用服务中启用主体身份验证。我可以通过 C# 代码获取我的不记名 token :

public static AuthenticationResult GetS2SAccessTokenForProdMSA()
{
return GetS2SAccessToken(authority, resource, clientId, clientSecret);
}

static AuthenticationResult GetS2SAccessToken(string authority, string resource, string clientId, string clientSecret)
{
var clientCredential = new ClientCredential(clientId, clientSecret);
AuthenticationContext context = new AuthenticationContext(authority, false);
AuthenticationResult authenticationResult = context.AcquireTokenAsync(resource, clientCredential).Result;
return authenticationResult;
}

如果我想通过 JavaScript 获取我的不记名 token ,例如:

$.ajax({
url: 'https://login.microsoftonline.com/1640e15a-2d4c-4903-8b89-a00c52ac3c17/oauth2/token',
type: 'POST',
crossOrigin: true,
data: 'resource=https://foobar' +
'&client_id=68b9a002-d6f9-4732-9c9c-893b2c60ba42' +
'&client_secret=<secret>' +
'&grant_type=client_credentials',
contentType: 'application/x-www-form-urlencoded',
success: function (returndata) {
alert(formData);
},
error: function (errordata) {
alert(errordata.statusText);
}
});

我在 Chrome 中收到错误消息:

No 'Access-Control-Allow-Origin' header is present on the requested resource

但在 Fiddler 中,我可以使用不记名 token 看到成功的答案(在 Firefox 中出现相同的错误,但在 IE 11 中则不然)。

为什么无法通过 AJAX 请求请求 token ?

我错过了什么吗?

干杯

最佳答案

您无法使用客户端凭据从前端获取 token 。

相反,您必须使用隐式授予流在重定向后获取片段中的访问 token ,或将其从应用程序的后端传递到前端。

在这里您可以找到一个 AngularJS 应用程序示例:https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp .

另一种选择是不从前端调用 API,而是从后端调用它们。

错误原因是 Azure AD 不允许 CORS

顺便说一句,永远不要将您的客户端 key 放在前端。

关于c# - API 应用程序的 Azure 服务主体身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42624229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com