使用azure隐式流检索oauth访问令牌

时间:2018-01-10 10:08:02

标签: node.js azure active-directory

我使用基于azure节点的api来设置隐含的oauth v2流。在浏览器中输入网址后,虽然页面没有返回任何内容 - 浏览器网址会在重定向后更新为包含access_token和其他参数。我希望通过使用curl命令来提取它们,并在服务器端的nodejs中执行它。我一直试图发送下面的卷曲请求:

curl -i -g -H "Content-Type: application/json" -d "{"client_id":"[client_id]","response_type":"id_token+token","scope":"open_id api://[client_id]/access_as_user","response_mode":"fragment","state":"12345","nonce":"678910","redirect_uri":"http://localhost:3000/account/"}" 'https://login.microsoftonline.com/microsoft.onmicrosoft.com/oauth2/v2.0/authorize'

我得到的错误是:

HTTP/1.1 400 Bad Request
Cache-Control: private
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.5
Strict-Transport-Security: max-age=31536000; includeSubDomains
X-Content-Type-Options: nosniff
x-ms-request-id: b64ffac8-500a-48c9-ab61-7e64d74f0600
Set-Cookie: x-ms-gateway-slice=005; path=/; secure; HttpOnly
Set-Cookie: stsservicecookie=ests; path=/; secure; HttpOnly
X-Powered-By: ASP.NET
Date: Wed, 10 Jan 2018 09:02:16 GMT
Content-Length: 381

{"error":"invalid_request","error_description":"AADSTS90004: Malformed JSON\r\nTrace ID: b64ffac8-500a-48c9-ab61-7e64d74f0600\r\nCorrelation ID: 64d444f1-1dd6-4ba6-b75f-876778515239\r\nTimestamp: 2018-01-10 09:02:19Z","error_codes":[90004],"timestamp":"2018-01-10 09:02:19Z","trace_id":"b64ffac8-500a-48c9-ab61-7e64d74f0600","correlation_id":"64d444f1-1dd6-4ba6-b75f-876778515239"}

此时,我创建了一个节点应用程序,并使用adal-js检索终点上的访问令牌。

var express = require('express');

var AuthenticationContext = require('adal-node').AuthenticationContext;

var app = express();
var authorityUrl = 'https://login.windows.net/' + sampleParameters.tenant + '/oauth2/authorize?response_type=code&client_id=<client_id>&response_type=<response_type>&scope=api://<client_id>/access_as_user&response_mode=<response_mode>&state=<state>&nonce=<nonce>&redirect_uri=http://localhost:3000/account';

app.get('/account', function(req, res) {
  var authenticationContext = new AuthenticationContext(authorityUrl);
  authenticationContext.acquireToken(authorityUrl, function(err, response) {
    var message = '';
    if (err) {
      message = 'error: ' + err.message + '\n';
    }
    message += 'response: ' + JSON.stringify(response);

    if (err) {
      res.send(message);
      return;
    }
});
app.listen(3000);

我在浏览器上看到的错误,当我登录时:(请注意,上面已输入所有有效参数)

Error: acquireToken requires a function callback parameter.

任何人都可以帮助解决问题 - 尝试从输出中提取访问令牌吗?

参考链接:https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-v2-protocols-implicit

1 个答案:

答案 0 :(得分:0)

基本上,implicit flow用于JavaScript单页面应用程序(SPA),而adal-node用于Azure AD v1.0端点,而不是用于v2.0端点。请参阅Azure AD v2.0 authentication libraries

对于您的场景(Node.js Web API),我建议您使用OAuth 2.0 authorization code flow来保护您的Web API。 Here是使用Node.js保护Web API的分步说明。