最近在写一些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了

以下就是我们获取的信息

SharePoint Online 使用 adal js 获取access token的更多相关文章

  1. 基于DotNetOpenAuth的OAuth实现示例代码: 获取access token

    1. 场景 根据OAuth 2.0规范,该场景发生于下面的流程图中的(D)(E)节点,根据已经得到的authorization code获取access token. 2. 实现环境 DotNetOp ...

  2. 工作笔记—新浪微博Oauth2.0授权 获取Access Token (java)

    java发送新浪微博,一下博客从注册到发布第一条微博很详细 利用java语言在eclipse下实现在新浪微博开发平台发微博:http://blog.csdn.net/michellehsiao/art ...

  3. 新浪微博Oauth2.0授权 获取Access Token

    新浪微博开放平台提供了丰富的API接口,利用这些接口,开发者能够开发出独具特色的微博应用.但是,大部分接口都需要用户授权给应用,应用利用授权得到的Access Token来调用相应的接口来获取内容. ...

  4. 通过重复运行的Microsoft Flow由OAuth认证后获取Access Token并将其更新到实体记录

    我是微软Dynamcis 365 & Power Platform方面的工程师罗勇,也是2015年7月到2018年6月连续三年Dynamics CRM/Business Solutions方面 ...

  5. 自定义菜单和高级接口-获取Access Token

    自定义菜单和高级接口都需要使用APPID和AppSecret来创建. 对应暂时没有这些权限的微信公众账号,开发者可以申请测试账号来体验和测试体验微信公众平台的所有高级接口的功能.链接 https:// ...

  6. 【Azure Developer】使用 Microsoft Authentication Libraries (MSAL) 如何来获取Token呢 (通过用户名和密码方式获取Access Token)

    问题描述 在上一篇博文<[Azure Developer]使用 adal4j(Azure Active Directory authentication library for Java)如何来 ...

  7. Azure AD, Endpoint Manger(Intune), SharePoint access token 的获取

    本章全是干货,干货,干货,重要的事情说三遍. 最近在研究Azure, Cloud相关的东西,项目中用的是Graph API(这个在下一章会相信介绍),可能是Graph API推出的时间比较晚,部分AP ...

  8. OAuth2.0 微博登陆网站功能的实现(一)获取用户授权及令牌 Access Token

    在登陆一些网站的时候,可以选择登陆方式为第三方登陆,例如微博登陆,以爱奇艺为例,进入首页,点击 ”登陆“,会弹出登录框: 除了本站登陆外,还可以选择其他第三方登陆,比如微博登陆.QQ 登陆.微信登陆等 ...

  9. 微信公众平台开发视频教程-03-获取Access Token和获取微信服务器IP,添加微信菜单

    1 获取access token 此token是以后每次调用微信接口都会带上的票据,token是公众号全局唯一票据,在调用其他接口之前都需要先得到token,taoken长度至少512个字符,通常用s ...

随机推荐

  1. 2.1FTP的简单传输

    第一个简单的FTP传输实例 from ftplib import FTP nonpassive = False filename = 'new_1.py' dirname = '.' sitename ...

  2. mysql存储过程造数

    性能测试时,数据库表通常需要很多数据,此时我们可以用存储过程来造数,以下代码mysql.Oracle都可以用 首先,先查看数据库表的设计,可以看到每张表有多少字段,分别都是什么类型,哪个字段是自动增长 ...

  3. SQL-7查找薪水涨幅超过15次的员工号emp_no以及其对应的涨幅次数t (group 与count)

    题目描述 查找薪水涨幅超过15次的员工号emp_no以及其对应的涨幅次数tCREATE TABLE `salaries` (`emp_no` int(11) NOT NULL,`salary` int ...

  4. tf 版本更新 记录

    tf 经常更新版本,网上教程又是各版本都有,且不标明版本,致使各种用法难以分清哪个新,哪个旧,这里做个记录,以前的博客我就不更新了,请大家见谅. tf.nn.rnn_cell 改为 tf.contri ...

  5. shell脚本实例-shell 分析系统瓶颈脚本

    #!/usr/bin/bash PS3="Your choice is: [10 for quit]" #检查是那个系统 os_check() { if [ -e /etc/red ...

  6. 解决Could not open Hibernate Session for transaction; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/transaction/spi/TransactionContext

    我使用的是5.2.8的hibernate的jar包,运行的时候却报错Could not open Hibernate Session for transaction; nested exception ...

  7. 一种基于SDR实现的被动GSM嗅探

    软件定义无线电(SDR)是一种无线电通信系统,简单来说,就是通过数字信号处理技术在通用可编程数字信号处理硬件平台上,利用软件定义来实现无线电台的各单元功能,从而对无线电信号进行调制.解调.测量.SDR ...

  8. ubantu 安装mysql 5.7 解决安装不提示设置密码问题

    1.安装Mysql sudo apt-get install mysql-server sudo apt-get install mysql-client sudo apt-get install l ...

  9. 记第十四届省赛参赛体会&第十三届

    emmm....时间还是很久远了 还是流水账 这次比赛我还是挺开心的 因为感觉我们余神就是一把宝剑,然后我是她的Buff 前面四道题就挺顺利都1A过了,十年余神就是强无敌呀 最后两分钟过了第五题,银牌 ...

  10. 2017第八届蓝桥杯C/C++ B组省赛-等差素数列

    标题:等差素数列 2,3,5,7,11,13,....是素数序列. 类似:7,37,67,97,127,157 这样完全由素数组成的等差数列,叫等差素数数列. 上边的数列公差为30,长度为6. 200 ...