【发布时间】:2017-07-26 05:46:16
【问题描述】:
我已经使用 REST 服务构建了一个简单的 API 应用程序。现在,我已在 Azure 应用服务中启用主体身份验证。我可以通过 C# 代码获取我的不记名令牌:
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 获取我的不记名令牌,例如:
$.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 中收到一条错误消息:
请求中没有“Access-Control-Allow-Origin”标头 资源
但在 Fiddler 中,我可以使用不记名令牌看到成功的答案(在 Firefox 中同样的错误,但在 IE 11 中没有)。
为什么无法通过 AJAX 请求请求令牌?
我错过了什么吗?
干杯
【问题讨论】:
-
您正在向与网页不同的域发出请求,因此您需要allow CORS on the server
-
我已经在 API 应用程序本身中启用了 CORS。但是我应该如何为 URL login.microsoftonline.com/1640e15a-2d4c-4903-8b89-a00c52ac3c17/… 启用 CORS?
-
我不明白,为什么我无法从任何 URL 请求不记名令牌。