问题描述

在上一篇博文 “【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);
 
最后,实现 /auth 和 /redirect 接口代码 (/auth 是登录AAD的入口,登录成功后由AAD回调/redirect接口,输出Access Token内容
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)的更多相关文章

  1. 【Azure 应用服务】NodeJS Express + MSAL 应用实现AAD集成登录并部署在App Service Linux环境中的实现步骤

    问题描述 实现部署NodeJS Express应用在App Service Linux环境中,并且使用Microsoft Authentication  Library(MSAL)来实现登录Azure ...

  2. 【Azure 应用服务】NodeJS Express + MSAL 实现API应用Token认证(AAD OAuth2 idToken)的认证实验 -- passport.authenticate('oauth-bearer', {session: false})

    问题描述 在前两篇博文中,对NodeJS Express应用 使用MSAL + AAD实现用户登录并获取用户信息,获取Authorization信息 ( ID Token, Access Token) ...

  3. Nodejs&express+mongodb完成简单用户登录(即Nodejs入门)

    刚了解nodejs,发现nodejs配置起来不复杂,但也有很多需要注意的地方,今天就记录一下,以后也可拿出来看看. 要完成这个简单的示例,从零开始,走三步就行了. 一.搭建开发环境 二.创建项目(ex ...

  4. nodejs+express+mysql 增删改查

    之前,一直使用的是nodejs+thinkjs来完成自己所需的项目需求,而对于nodejs中另外一中应用框架express却了解的少之又少,这两天就简单的了解了一下如何使用express来做一些数据库 ...

  5. nodejs学习篇 (1)webstorm创建nodejs + express + jade 的web 项目

    之前简单了解过nodejs,觉得用nodejs来做个网站也太麻烦了,要自己拼html的字符串返回,这能做网站嘛? 最近看到使用jade模板来开发,觉得挺新奇的,于是试了一把,也了解了一些特性,算是个新 ...

  6. 使用nodejs+express+socketio+mysql搭建聊天室

    使用nodejs+express+socketio+mysql搭建聊天室 nodejs相关的资料已经很多了,我也是学习中吧,于是把socket的教程看了下,学着做了个聊天室,然后加入简单的操作mysq ...

  7. CentOS编译安装NodeJS+Express

    NodeJS是基于Chrome’s Javascript runtime,也就是Google V8引擎执行Javascript的快速构建网络服务及应用的平台,其优点有: 在CentOS编译安装Node ...

  8. nodejs+express使用html和jade

    nodejs+express经常会看到使用jade视图引擎,但是有些人想要访问普通的html页面,这也是可以的: var express = require('express'); var port ...

  9. nodejs+express中设置登录拦截器

    在nodejs+express中,采用nodejs后端路由控制用户登录后,为了加强前端的安全性控制,阻止用户通过在浏览器地址栏中输入地址访问后台接口,在app.js中需要加入拦截器进行拦截: /*** ...

随机推荐

  1. indexOf返回值问题

    String s = "aoood";System.out.println(s.indexOf(""));//返回0 System.out.println(s. ...

  2. vue中执行npm run build报错解决方法?

    遇到了执行npm run build 后报错: [build:js ] Module not found: Error: Can't resolve 'scss-loader' in 'D:\work ...

  3. TINY语言采用递归下降分析法编写语法分析程序

    目录 自顶向下分析方法 TINY文法 消左提左.构造first follow 基本思想 python构造源码 运行结果 参考来源:聊聊编译原理(二) - 语法分析 自顶向下分析方法 自顶向下分析方法: ...

  4. IP和静态路由技术概述

    1. IP地址的构成 IP地址:32比特的二进制数字,通常采用点分十进制方式表示. IP地址由两部分组成. 网络号码字段(Net-id)用于区分不同的网络.网络号码字段的前几位成为类别字段(又称为类别 ...

  5. jquery 日期插件datePicker使用

    1.将下载下来的DatePicker压缩包解压后整个放入项目中,不可只引入js和css 2.在html中指定input位置加上class="Wdate"(默认样式不加也可正常显示) ...

  6. Web安全中的常见Session攻击(预测+劫持+固定)

    攻击者至少可以通过以下三种方式来获取一个有效的session标识符: 1.预测 2.捕获(劫持) 3.固定 一.会话预测 预测这种方式,也就是攻击者需要猜测出系统中使用的有效的session标识符(P ...

  7. 推荐一个我写的Python库——PyNAS

    介绍 PyNAS是一个以Python的Updog的库为基础,制作而来的库 安装 pip安装(推荐) pip install PyNAS 源码安装(推荐) Github: git clone https ...

  8. java高级用法之:在JNA中使用类型映射

    目录 简介 类型映射的本质 TypeMapper NativeMapped 总结 简介 JNA中有很多种映射,library的映射,函数的映射还有函数参数和返回值的映射,libary和函数的映射比较简 ...

  9. js 改变页面元素的内容

    改变页面标签里的内容 (方法) innerText innerHTML (常用)   代码示例 <div></div> <p> 我是文字 <span>1 ...

  10. react实战系列 —— 起步(mockjs、第一个模块、docusaurus)

    其他章节请看: react实战 系列 起步 本篇我们首先引入 mockjs ,然后进入 spug 系统,接着模仿"任务计划"模块实现一个类似的一级导航页面("My任务计划 ...