【Azure 應(yīng)用服務(wù)】NodeJS Express + MSAL 應(yīng)用實現(xiàn)AAD登錄并獲取AccessToken -- cca.acquireTokenByCode(tokenRequest)

問題描述

在上一篇博文 “【Azure 應(yīng)用服務(wù)】NodeJS Express + MSAL 應(yīng)用實現(xiàn)AAD集成登錄并部署在App Service Linux環(huán)境中的實現(xiàn)步驟”中溺拱,實現(xiàn)了登錄凰兑,并獲取登錄用戶在AAD中的個人信息似舵,但是沒有一個顯示的方法輸出所獲取到的Access Token,則通過新建Express項目衰腌,加載MSAL的代碼實現(xiàn)此目的。

實現(xiàn)步驟

第一步:創(chuàng)建 NodeJS Express項目觅赊,并添加@azure/msal-node 項目包

前提條件:安裝 Node.js 和 VS Code

使用npm安全express項目生成器

npm install -g express-generator

在當(dāng)前目錄在生成 express項目默認(rèn)文件

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 參數(shù) clientId, authority 和 clientSecret (與上一篇博文中第一步相同, 也需要添加 http://localhost:3000/redirect 在 AAD注冊應(yīng)用的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";

然后根據(jù)上一步的config參數(shù)初始化 msal confidential client applicaiton對象

// Initialize MSAL Node object using authentication parameters
const cca = new msal.ConfidentialClientApplication(config);

最后,實現(xiàn) /auth 和 /redirect 接口代碼 (/auth 是登錄AAD的入口,登錄成功后由AAD回調(diào)/redirect接口棕所,輸出Access Token內(nèi)容

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;

運行效果動畫展示:

show access token.gif

參考資料

NodeJS Express + MSAL 應(yīng)用實現(xiàn)AAD集成登錄并部署在App Service Linux環(huán)境中的實現(xiàn)步驟: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

當(dāng)在復(fù)雜的環(huán)境中面臨問題仗嗦,格物之道需:濁而靜之徐清沽一,安以動之徐生秘案。 云中,恰是如此!

分類: 【Azure 應(yīng)用服務(wù)】, 【Azure 環(huán)境】, 【Azure Developer】

標(biāo)簽: App Service, Azure Developer, Azure 環(huán)境, MSAL AAD, cca.acquireTokenByCode(tokenRequest)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末莫鸭,一起剝皮案震驚了整個濱河市闹丐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌被因,老刑警劉巖卿拴,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異梨与,居然都是意外死亡堕花,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進店門粥鞋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來缘挽,“玉大人,你說我怎么就攤上這事呻粹『韭” “怎么了?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵等浊,是天一觀的道長腮郊。 經(jīng)常有香客問我,道長筹燕,這世上最難降的妖魔是什么轧飞? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮撒踪,結(jié)果婚禮上过咬,老公的妹妹穿的比我還像新娘。我一直安慰自己制妄,他們只是感情好掸绞,可當(dāng)我...
    茶點故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著忍捡,像睡著了一般集漾。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上砸脊,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天具篇,我揣著相機與錄音,去河邊找鬼凌埂。 笑死驱显,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的瞳抓。 我是一名探鬼主播栓霜,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼胳蛮,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了抚垄?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤荧恍,失蹤者是張志新(化名)和其女友劉穎摹菠,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體虹蓄,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡坐儿,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年逛漫,在試婚紗的時候發(fā)現(xiàn)自己被綠了投储。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片呕寝。...
    茶點故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡孽江,死狀恐怖辆琅,靈堂內(nèi)的尸體忽然破棺而出暇屋,到底是詐尸還是另有隱情扬霜,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布麦向,位于F島的核電站话告,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏卵慰。R本人自食惡果不足惜裳朋,卻給世界環(huán)境...
    茶點故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一暖眼、第九天 我趴在偏房一處隱蔽的房頂上張望惭缰。 院中可真熱鬧,春花似錦、人聲如沸昂羡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽蛹批。三九已至撰洗,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間腐芍,已是汗流浹背差导。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留猪勇,地道東北人设褐。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像泣刹,于是被迫代替她去往敵國和親助析。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容