2017-03-06 27 views
0

我已经使用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请求请求令牌?

我错过了什么吗?

欢呼声

+0

您正在向网页上的其他域请求,因此您需要[允许服务器上的CORS](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin -header-is-present-on-the-requested-resources) – stuartd

+0

我已经在API应用程序本身中启用了CORS。但是,我应该如何为网址https://login.microsoftonline.com/1640e15a-2d4c-4903-8b89-a00c52ac3c17/oauth2/token启用CORS? – user2191213

+0

我不明白,为什么我无法从任何URL请求不记名令牌。 – user2191213

回答

1

您无法从客户端证书的前端获取令牌。

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

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

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

错误的原因是Azure AD不允许CORS

顺便说一句,永远不要把你的客户的秘密放在前端。

+0

感谢您的支持!从没有Azure AD身份验证的网页调用Azure API应用程序WebService的最佳做法是什么?网页是公开的,但是WebService调用应该作为一种服务用户来调用。 – user2191213

+0

您的前端可以在其后端调用公共端点。然后端点可以通过客户端凭证流(客户端ID +客户端密钥)与Azure AD进行身份验证,并使用访问令牌调用We​​b服务。这样你的客户机密就保密了,你可以控制可以做什么。您可以缓存访问令牌+刷新令牌,因此您不需要每次从后端进行身份验证。 ADAL为你做得非常好。 – juunas

相关问题