SharePoint Online 使用 adal js 获取access token

最近在写一些SharePoint 的sample code, 有兴趣的小伙伴可以查看我的GitHub.

今天给大家介绍SharePoint Framework (SPFx  )web part 当中怎么去使用adal js 去获取 使用Office 365 Graph API 的access token.

 

首先,在此感谢我的同事闫明明研究出来怎样获取adal js access token.

 

首先我们打开office 365 tenant 里面的Admin center.  然后打开 Azure AD Tab

 

 

打开Azure 之后, 点 Azure Active Directory -> App registrations -> New application registration

 

我们创建之后, 会要求我们输入这些信息: Name & Sign-on URL

Name是项目的名称

Application type 选 Web app / API

Sign-on url 是 项目登录Azure AD 的URL.

 

我们创建好app 之后, 我们会在app 设置页面:

Application ID 是我们后面需要使用的GUID.

 

 下面我们要改动一下 manifest 文档

 

我們需要把图中的oauth2AllowImplicitFlow 的value 改为true. 

然后save 改动.

 

 

接下来,我们需要去Settings _> Required  permissions 做一些改动

我们在delegated permissions里面选上 sign in and read user profile 然后 save changes

 

很多小伙伴有问题 为什么不使用application permissions  而使用 delegated permissions. 

Application permissions:

Application permissions are used when the application calls the API as itself

App 本身call API

Delegated permissions:

Delegated permissions works when you want to call the Web API as the logged on user. 

使用app的登录用户call api

来自Stack Overflow

 区别其实很明显了.  在于app本身 call api 还是使用用户call api.

 

在我们save 之后, 需要再required permissions grant permissions, 不然系统不会改动配置

 

 

所有在Azure端设置的都结束了. 我们可以打开SPFx Web Part 啦

我们首先要添加这两个文件到helloWorld文件夹里面(注解: 没有使用仍和JavaScript的framework)

在IAdalConfig.ts 的interface当中添加以下TS代码:

export interface IAdalConfig extends adal.Config {
    popUp?: boolean;
    callback?: (error: any, token: string) => void;
    webPartId?: string;
  }

 

添加WebPartAuthenticationContext.js 代码:

代码链接

const AuthenticationContext = require('adal-angular');

AuthenticationContext.prototype._getItemSuper = AuthenticationContext.prototype._getItem;
AuthenticationContext.prototype._saveItemSuper = AuthenticationContext.prototype._saveItem;
AuthenticationContext.prototype.handleWindowCallbackSuper = AuthenticationContext.prototype.handleWindowCallback;
AuthenticationContext.prototype._renewTokenSuper = AuthenticationContext.prototype._renewToken;
AuthenticationContext.prototype.getRequestInfoSuper = AuthenticationContext.prototype.getRequestInfo;
AuthenticationContext.prototype._addAdalFrameSuper = AuthenticationContext.prototype._addAdalFrame;

AuthenticationContext.prototype._getItem = function (key) {
  if (this.config.webPartId) {
    key = this.config.webPartId + '_' + key;
  }

  return this._getItemSuper(key);
};

AuthenticationContext.prototype._saveItem = function (key, object) {
  if (this.config.webPartId) {
    key = this.config.webPartId + '_' + key;
  }

  return this._saveItemSuper(key, object);
};

AuthenticationContext.prototype.handleWindowCallback = function (hash) {
  if (hash == null) {
    hash = window.location.hash;
  }

  if (!this.isCallback(hash)) {
    return;
  }

  var requestInfo = this.getRequestInfo(hash);
  if (requestInfo.requestType === this.REQUEST_TYPE.LOGIN) {
    return this.handleWindowCallbackSuper(hash);
  }

  var resource = this._getResourceFromState(requestInfo.stateResponse);
  if (!resource || resource.length === 0) {
    return;
  }

  if (this._getItem(this.CONSTANTS.STORAGE.RENEW_STATUS + resource) === this.CONSTANTS.TOKEN_RENEW_STATUS_IN_PROGRESS) {
    return this.handleWindowCallbackSuper(hash);
  }
}

AuthenticationContext.prototype._renewToken = function (resource, callback) {
  this._renewTokenSuper(resource, callback);
  var _renewStates = this._getItem('renewStates');
  if (_renewStates) {
    _renewStates = _renewStates.split(',');
  }
  else {
    _renewStates = [];
  }
  _renewStates.push(this.config.state);
  this._saveItem('renewStates', _renewStates);
}

AuthenticationContext.prototype.getRequestInfo = function (hash) {
  var requestInfo = this.getRequestInfoSuper(hash);
  var _renewStates = this._getItem('renewStates');
  if (!_renewStates) {
    return requestInfo;
  }

  _renewStates = _renewStates.split(';');
  for (var i = 0; i < _renewStates.length; i++) {
    if (_renewStates[i] === requestInfo.stateResponse) {
      requestInfo.requestType = this.REQUEST_TYPE.RENEW_TOKEN;
      requestInfo.stateMatch = true;
      break;
    }
  }

  return requestInfo;
}

AuthenticationContext.prototype._addAdalFrame = function (iframeId) {
  var adalFrame = this._addAdalFrameSuper(iframeId);
  adalFrame.style.width = adalFrame.style.height = '106px';
  return adalFrame;
}

window.AuthenticationContext = function() {
  return undefined;
}

 

打开XXXwebpart.ts

添加以下代码到render里面

ClientId是Azure AD 前面注册的ID

Tenant 为你office365 的tenant ID.

var authContext = new AuthenticationContext({
        clientId: 'your_content_id',
        instance: "https://login.microsoftonline.com/",
        tenant: "your_tenant.onmicrosoft.com",
        // postLogoutRedirectUri: 'https://localhost:4321/temp/workbench.html'
      });
      // Make an AJAX request to the Microsoft Graph API and print the response as JSON.
      var getToken;
      var getCurrentUser = function (access_token) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
        xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            // Do something with the response
            
            getToken=JSON.stringify(JSON.parse(xhr.responseText), null, '  ');
            console.log('get Graph APi information=='+getToken);
          } else {
            // TODO: Do something with the error (or non-200 responses)
          //  console.log(' error');
          }
        };
        xhr.send();
      }
 
      if (authContext.isCallback(window.location.hash)) {
        // Handle redirect after token requests
        authContext.handleWindowCallback();
        var err = authContext.getLoginError();
        if (err) {
          // TODO: Handle errors signing in and getting tokens
          console.log('login error');
        }
      } else {
        // If logged in, get access token and make an API request
        var user = authContext.getCachedUser();
        if (user) {
         
 
          // Get an access token to the Microsoft Graph API
          authContext.acquireToken(
            'https://graph.microsoft.com',
            function (error, token) {
              if (error || !token) {
                // TODO: Handle error obtaining access token
                console.log('Token error');
                return;
              }
              // Use the access token
              console.log('token=='+token);
              getCurrentUser(token);
            }
          );
        } else {
          authContext.login();
        }
       
      }

 

接下来我们就可以debug了

 

以下就是我们获取的信息

 

转载于:https://www.cnblogs.com/TheMiao/p/9955457.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值