【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD登录并获取AccessToken -- cca.acquireTokenByCode(tokenRequest)
问题描述
在上一篇博文 “【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD集成登录并部署在App Service Linux环境中的实现步骤”中,实现了登录,并获取登录用户在AAD中的个人信息,但是没有一个显示的方法输出所获取到的Access Token,则通过新建Express项目,加载MSAL的代码实现此目的。
实现步骤
第一步:创建 NodeJS Express项目,并添加@azure/msal-node 项目包
前提条件:安装 Node.js 和 VS Code
使用npm安全express项目生成器
npm install -g express-generator
在当前目录在生成 express项目默认文件
express --view=hbs
开始生成项目文件
npm install
安装MSAL package
npm install --save @azure/msal-node
项目生成后的完整路径
myExpressWebApp/
├── bin/
| └── wwww
├── public/
| ├── images/
| ├── javascript/
| └── stylesheets/
| └── style.css
├── routes/
| ├── index.js
| └── users.js
├── views/
| ├── error.hbs
| ├── index.hbs
| └── layout.hbs
├── app.js
└── package.json
第二步:在 app.js 中添加 MSAL object,添加 '/auth' 接口登录AAD并获取Access Token
引入 msal 对象
const msal = require('@azure/msal-node');
配置AAD Authentication 参数 clientId, authority 和 clientSecret (与上一篇博文中第一步相同, 也需要添加 http://localhost:3000/redirect 在 AAD注册应用的Redirect URIs中)。
// Authentication parameters
const config = {
auth: {
clientId: " Enter_the_Application_Id_Here",
authority: "https://login.partner.microsoftonline.cn/<#Enter_the_Tenant_Info_Here>",
clientSecret: "xxxxxx.xxxxxxxxxxxxxxxxx" #Enter_the_Client_Secret_Here
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
}
}
}; const REDIRECT_URI = "http://localhost:3000/redirect";
然后根据上一步的config参数初始化 msal confidential client applicaiton对象
// Initialize MSAL Node object using authentication parameters
const cca = new msal.ConfidentialClientApplication(config);
app.get('/auth', (req, res) => {
// Construct a request object for auth code
const authCodeUrlParameters = {
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// Request auth code, then redirect
cca.getAuthCodeUrl(authCodeUrlParameters)
.then((response) => {
res.redirect(response);
}).catch((error) => res.send(error));
});
app.get('/redirect', (req, res) => {
// Use the auth code in redirect request to construct
// a token request object
const tokenRequest = {
code: req.query.code,
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// Exchange the auth code for tokens
cca.acquireTokenByCode(tokenRequest)
.then((response) => {
res.send(response);
}).catch((error) => res.status(500).send(error));
});
完整 app.js 代码为:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const msal = require('@azure/msal-node');
// Authentication parameters
const config = {
auth: {
clientId: " Enter_the_Application_Id_Here",
authority: "https://login.partner.microsoftonline.cn/<#Enter_the_Tenant_Info_Here>",
clientSecret: "xxxxxx.xxxxxxxxxxxxxxxxx" #Enter_the_Client_Secret_Here
},
system: {
loggerOptions: {
loggerCallback(loglevel, message, containsPii) {
console.log(message);
},
piiLoggingEnabled: false,
logLevel: msal.LogLevel.Verbose,
}
}
};
const REDIRECT_URI = "http://localhost:3000/redirect";
// Initialize MSAL Node object using authentication parameters
const cca = new msal.ConfidentialClientApplication(config);
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.get('/auth', (req, res) => {
// Construct a request object for auth code
const authCodeUrlParameters = {
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// Request auth code, then redirect
cca.getAuthCodeUrl(authCodeUrlParameters)
.then((response) => {
res.redirect(response);
}).catch((error) => res.send(error));
});
app.get('/redirect', (req, res) => {
// Use the auth code in redirect request to construct
// a token request object
const tokenRequest = {
code: req.query.code,
scopes: ["user.read"],
redirectUri: REDIRECT_URI,
};
// Exchange the auth code for tokens
cca.acquireTokenByCode(tokenRequest)
.then((response) => {
res.send(response);
}).catch((error) => res.status(500).send(error));
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
运行效果动画展示:

参考资料
NodeJS Express + MSAL 应用实现AAD集成登录并部署在App Service Linux环境中的实现步骤:https://www.cnblogs.com/lulight/p/16353145.html
Tutorial: Sign in users and acquire a token for Microsoft Graph in a Node.js & Express web app: https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-nodejs-webapp-msal
Example: Acquiring tokens with ADAL Node vs. MSAL Node:https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-node-migration#example-acquiring-tokens-with-adal-node-vs-msal-node
【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD登录并获取AccessToken -- cca.acquireTokenByCode(tokenRequest)的更多相关文章
- 【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD集成登录并部署在App Service Linux环境中的实现步骤
问题描述 实现部署NodeJS Express应用在App Service Linux环境中,并且使用Microsoft Authentication Library(MSAL)来实现登录Azure ...
- 【Azure 应用服务】NodeJS Express + MSAL 实现API应用Token认证(AAD OAuth2 idToken)的认证实验 -- passport.authenticate('oauth-bearer', {session: false})
问题描述 在前两篇博文中,对NodeJS Express应用 使用MSAL + AAD实现用户登录并获取用户信息,获取Authorization信息 ( ID Token, Access Token) ...
- Nodejs&express+mongodb完成简单用户登录(即Nodejs入门)
刚了解nodejs,发现nodejs配置起来不复杂,但也有很多需要注意的地方,今天就记录一下,以后也可拿出来看看. 要完成这个简单的示例,从零开始,走三步就行了. 一.搭建开发环境 二.创建项目(ex ...
- nodejs+express+mysql 增删改查
之前,一直使用的是nodejs+thinkjs来完成自己所需的项目需求,而对于nodejs中另外一中应用框架express却了解的少之又少,这两天就简单的了解了一下如何使用express来做一些数据库 ...
- nodejs学习篇 (1)webstorm创建nodejs + express + jade 的web 项目
之前简单了解过nodejs,觉得用nodejs来做个网站也太麻烦了,要自己拼html的字符串返回,这能做网站嘛? 最近看到使用jade模板来开发,觉得挺新奇的,于是试了一把,也了解了一些特性,算是个新 ...
- 使用nodejs+express+socketio+mysql搭建聊天室
使用nodejs+express+socketio+mysql搭建聊天室 nodejs相关的资料已经很多了,我也是学习中吧,于是把socket的教程看了下,学着做了个聊天室,然后加入简单的操作mysq ...
- CentOS编译安装NodeJS+Express
NodeJS是基于Chrome’s Javascript runtime,也就是Google V8引擎执行Javascript的快速构建网络服务及应用的平台,其优点有: 在CentOS编译安装Node ...
- nodejs+express使用html和jade
nodejs+express经常会看到使用jade视图引擎,但是有些人想要访问普通的html页面,这也是可以的: var express = require('express'); var port ...
- nodejs+express中设置登录拦截器
在nodejs+express中,采用nodejs后端路由控制用户登录后,为了加强前端的安全性控制,阻止用户通过在浏览器地址栏中输入地址访问后台接口,在app.js中需要加入拦截器进行拦截: /*** ...
随机推荐
- python---if、while、for
if语句 当出现选择情况的时候,就需要用到if语句. # 第一种语法 if 条件: # 冒号将条件和结果分开,不可缺少 结果1 结果2 # 条件为真执行结果1,然后结果2:否则直接结果2 # 第二种语 ...
- Mybatis-自定义类型处理器
类型转换器:mybatis中有一些常用的类型转换器,比如把Java中的short类型转换为mysql中的short类型:但是如果现在是Java中的Date类型,但是我想要存储到数据库中转换为Long类 ...
- LC-19
19. 删除链表的倒数第 N 个结点 思路基本直接出来,双指针,IndexFast 和 IndexSlow 中间相隔 N - 1, 这样 IndexFast 到了最后,IndexSlow 自然就是倒数 ...
- POP3协议(电子邮件邮局协议)中UIDL和TOP命令在实际使用中的作用
POP3是电子邮件协议中用于接收邮件的协议,相较于发送邮件的SMTP协议,POP3的命令要多一些.主要的命令有LIST.STAT.RETR.DELE.UIDL.TOP.QUIT,以及用于登录邮箱的US ...
- python3-认识内置对象,运算符,表达式
1 . 认识内置对象 在python中一切皆对象, 整数,实数,复数,字符串,列表,元组,字典,集合,zip, map, enumerate, filter , 函数 ,类 , 分类:内置对象,标准 ...
- 6.2 计划任务crond
创建.编辑计划任务的命令为crontab -e,查看当前计划任务的命令为crontab -l,删除某条计划任务的命令为crontab -r. 参数 作用 -e 编辑计划任务 -u 指定用户名称 -l ...
- IOC容器--1.12. 基于 Java 的容器配置
用Java的方式配置Spring ,不使用Spring的XML配置,全权交给Java来做 JavaConfig是Spring的一个子项目,在Sring 4 之后成为核心功能 这种纯Java的配置方式 ...
- 【翻译】ScyllaDB数据建模的最佳实践
文章翻译自Scylla官方文档:https://www.scylladb.com/2019/08/20/best-practices-for-data-modeling/ 转载请注明出处:https: ...
- 基于SqlSugar的开发框架的循序渐进介绍(1)--框架基础类的设计和使用
在实际项目开发中,我们可能会碰到各种各样的项目环境,有些项目需要一个大而全的整体框架来支撑开发,有些中小项目这需要一些简单便捷的系统框架灵活开发.目前大型一点的框架,可以采用ABP或者ABP VNex ...
- 论文解读(NGCF)《LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation》
论文信息 论文标题:LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation论文作者:Xiangn ...