简体   繁体   English

Javascript AzureAd消费休息服务

[英]Javascript AzureAd Consume Rest Service

RestAPI : I have a Rest API running Asp Core with AzureAd Authentication. RestAPI :我有一个Rest API,运行带有AzureAd身份验证的Asp Core。

WebApp : I have a separate WebApplication running Asp Core as backend, with Javascript frontend. WebApp :我有一个单独的WebApplication,它运行Asp Core作为后端,并带有Javascript前端。

The WebApp backend authenticates through AzureAd, and then against the RestAPI to check if a user is registred. WebApp后端通过AzureAd进行身份验证,然后通过RestAPI进行身份验证以检查用户是否已注册。

I want the javascript client to be able to consume the Rest API directly. 我希望javascript客户端能够直接使用Rest API。 How should i go about this without exposing the accesstoken? 我应该如何处理而不暴露访问令牌?

I could go about sending the request from Javascript to WebApp Backend -> Rest API. 我可以将请求从Javascript发送到WebApp后端-> Rest API。 But i really want to avoid this, because of unnecessary code. 但是我真的想避免这种情况,因为不必要的代码。

In this scenario, you can try to implement ADAL for js in your JS client. 在这种情况下,您可以尝试在JS客户端中为js实现ADAL Leveraging **adal** to gain the authentication token, and when you call your Web Api, it will add the authentication header in HTTP requests. 利用**adal**获得身份验证令牌,当您调用Web Api时,它将在HTTP请求中添加身份验证标头。

EG 例如

Suppose we want to call the Microsoft Graph API from our JS client.we develop a node.js script that uses request to call the Microsoft Graph API for groups to create a new Security Group. 假设我们想从JS客户端调用Microsoft Graph API。我们开发了一个node.js脚本,该脚本使用请求来为组调用Microsoft Graph API,以创建新的安全组。

The following code shows how the API is consumed from that script. 以下代码显示了如何从该脚本使用API​​。 Note that the token and the name are passed by parameter. 请注意,令牌和名称是通过参数传递的。 Additionally, this function returns a Promise that is successfully resolved when the group is correctly created and rejected when is not. 此外,此函数还返回一个Promise,该Promise在正确创建该组时会成功解决,而在未正确创建时会被拒绝。

var request = require('request');

function createGroup(token, name) {
  return new Promise((resolve, reject) => {
    const options = {
      method: 'POST',
      url: 'https://graph.microsoft.com/v1.0/groups/',
      headers: {
        'Authorization': 'Bearer ' + token,
        'content-type': 'application/json'
      },
      body: JSON.stringify({
        "displayName": name,
        "mailEnabled": false,
        "securityEnabled": true
      })
    };

    request(options, (error, response, body) => {
      const result = JSON.parse(body);
      if (!error && response.statusCode == 204) {
        resolve(result.value);
      } else {
        reject(result);
      }
    });
  });
}

In order to call Microsoft Graph API, we needed to be authenticated and that is why in the previous section we have a token as a parameter of the function which was used to perform the request. 为了调用Microsoft Graph API,我们需要进行身份验证,这就是为什么在上一节中,我们有一个令牌作为用于执行请求的函数的参数。

we should add the following code to generate the token. 我们应该添加以下代码来生成令牌。 Note that we are using the adal npm package to do this easier, calling the acquireTokenWithClientCredentials method of the AuthenticationContext object. 请注意,我们正在使用adal npm软件包来简化此操作,调用AuthenticationContext对象的acquisitionTokenWithClientCredentials方法。 Additionally, we have some constants that need to be updated with the client id and secret obtained before as well as the tenant name. 此外,我们还有一些常量需要使用之前获取的客户端ID和密码以及租户名称进行更新。

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

const TENANT = "{tenant-name-here}.onmicrosoft.com";
const CLIENT_ID = "{Application-id-here}";
const CLIENT_SECRET = "{Application-key-here}";

function getToken() {
  return new Promise((resolve, reject) => {
    const authContext = new adal.AuthenticationContext(`https://login.microsoftonline.com/${TENANT}`);
    authContext.acquireTokenWithClientCredentials(GRAPH_URL, CLIENT_ID, CLIENT_SECRET, (err, tokenRes) => {
      if (err) { reject(err); }
      resolve(tokenRes.accessToken);
    });
  });

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM