AzureAD - 当我通过 AzureAD 进行身份验证时,我在检索用户信息(特别是员工编号)时遇到问题

问题描述 投票:0回答:1

我有一个 React 前端,可以对用户进行身份验证并获取具有我的 API 范围的访问令牌。我在后端发出请求时使用此令牌来验证会话,并且我能够验证用户。但是,我无法检索员工编号,而某些配置需要该编号。我是否错过了在 Azure 中配置某些内容的过程?有没有更简单的方法获取员工编号?

我使用的是passport.js,这是我的配置:

const passportConfig = {
  credentials: {
    tenantID: process.env.TENANT_ID,
    clientID: process.env.CLIENT_ID,
  },
  metadata: {
    authority: 'login.microsoftonline.com',
    discovery: '.well-known/openid-configuration',
    version: 'v2.0',
  },
  settings: {
    validateIssuer: true,
    passReqToCallback: true,
    loggingLevel: 'error',
    loggingNoPII: true,
  },
};

const bearerStrategy = new passportAzureAd.BearerStrategy({
  identityMetadata: `https://${passportConfig.metadata.authority}/${passportConfig.credentials.tenantID}/${passportConfig.metadata.version}/${passportConfig.metadata.discovery}`,
  issuer: `https://${passportConfig.metadata.authority}/${passportConfig.credentials.tenantID}/${passportConfig.metadata.version}`,
  clientID: passportConfig.credentials.clientID,
  audience: passportConfig.credentials.clientID,
  validateIssuer: passportConfig.settings.validateIssuer,
  passReqToCallback: passportConfig.settings.passReqToCallback,
  loggingLevel: passportConfig.settings.loggingLevel,
  loggingNoPII: passportConfig.settings.loggingNoPII,
}, (req, token, done) => {
  /**
   * If needed, pass down additional user info to route using the second argument below.
   * This information will be available in the req.user object.
   */
  return done(null, {}, token);
});

我尝试使用相同的访问令牌从后端向 Microsoft Graph API 发出请求,但它抛出了一个错误,表明受众无效,我认为这是因为令牌不具有该范围而引起的,但我不确定。

javascript reactjs node.js azure-active-directory passport.js
1个回答
0
投票

要从 Azure AD 访问令牌获取员工编号,您需要请求

user.employeeId
范围。您可以通过将以下内容添加到 Passport.js 配置中的
scopes
数组来完成此操作:

scopes: ['https://graph.microsoft.com/.default', 'user.employeeId']

完成此操作后,您将能够从代码中的

req.user
对象检索员工编号。

这是我获取用户详细信息的方式

创建了一个文件(例如,

auth.js
)来配置 Passport.js

const passport = require('passport');
const OIDCStrategy = require('passport-azure-ad').OIDCStrategy;

const config = {
  identityMetadata: 'https://login.microsoftonline.com/YOUR_TENANT_ID/v2.0/.well-known/openid-configuration',
  clientID: 'YOUR_CLIENT_ID',
  responseType: 'code id_token',
  responseMode: 'form_post',
  redirectUrl: 'http://localhost:3000/',
  allowHttpForRedirectUrl: true,
  clientSecret: 'YOUR_CLIENT_SECRET',
  validateIssuer: false,
  passReqToCallback: true,
  scope: ['openid', 'profile'],
};

passport.use(
  new OIDCStrategy(config, (req, iss, sub, profile, accessToken, refreshToken, done) => {
    return done(null, profile);
  })
);

passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((obj, done) => {
  done(null, obj);
});

结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.