我已经使用REST服务构建了一个简单的API应用程序。现在我已经在Azure App Service中启用了主体认证。我能够用C#代码让我的承载令牌:针对API的Azure服务主体认证应用程序
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的一个错误说:
否“访问控制允许来源”标题存在于所请求的资源
但在Fiddler中,我可以看到成功的答案和我的无记名标记(在Firefox中出现同样的错误,但在IE 11中不存在)。
为什么无法通过AJAX请求请求令牌?
我错过了什么吗?
欢呼声
您正在向网页上的其他域请求,因此您需要[允许服务器上的CORS](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin -header-is-present-on-the-requested-resources) – stuartd
我已经在API应用程序本身中启用了CORS。但是,我应该如何为网址https://login.microsoftonline.com/1640e15a-2d4c-4903-8b89-a00c52ac3c17/oauth2/token启用CORS? – user2191213
我不明白,为什么我无法从任何URL请求不记名令牌。 – user2191213