如何从 Microsoft Azure AD 登录过程中获取用户主体名称

How to get User Principal Name from Microsoft Azure AD Login Process

我正在使用@azure/msal-angular 登录用户。我提供了以下 "consentScopes":

['openid', 'email', 'profile']

登录重定向过程有效,因为它将我重定向到“https://login.microsoftonline.com”URL,"scope" 参数如下所示:

&scope=email%20openid%20profile

到目前为止一切顺利,我登录,被重定向回我的站点,然后我打印出 MSAL 服务提供的 "getUser()" 方法(敏感值进行混淆处理):

displayableId: "D...Mm"
name: "Mo....as"
identityProvider: "htt...0"
userIdentifier: "OG....5"
idToken:
aud: "ca...20"
iss: "htt....0"
iat: 1..83
nbf: 15..83
exp: 15...83
acct: 0
aio: "42dg....R/XQoA"
auth_time: 159...282
email: "DM.....com"
name: "Mo....as"
nonce: "7bc....d95d"
oid: "8e8f....fc3"
platf: "1"
preferred_username: "DMol....om"
sub: "j0KKHsU....WMEB_H3fyU"
tid: "98f7abd.....6fbd5f9"
uti: "Eu4y.....cMAAA"
ver: "2.0"

此处未提供 UPN 值。经过研究我发现 1.0 版本默认 returned UPN。

我发现了这个有用的问题,其中包含很多信息,但实际上并没有回答问题:

以下为微软文档截图(https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims)

它明确指出 "profile" 范围应该 return 一个 "upn" 值。我不认为这是 @azure/msal-angular 包的问题,​​因为登录 URL 正在正确生成。

根据我对 2.0 和 oauth 的理解,UPN 是一个选项声明,您必须在应用程序注册中的清单或令牌配置中指定 -> 添加可选声明。如果我理解正确的话,那是在配置文件范围之上,我认为配置文件范围使 oidc 可以访问这些额外信息,但不一定将其包含在声明中。

当然我可能是错的,但我没有看到它在哪里声明配置文件将 return upn 令牌中的值?

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-optional-claims#configuring-groups-optional-claims

您得到的是 id token,它不包括 upn 声明,请参阅 doc

upn声明将包含在访问令牌中,要获取访问令牌,您可以参考示例here, which uses the Implicit grant flow

// app.module.ts
@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    // ...
    MsalModule.forRoot({
      auth: {
        clientId: 'Enter_the_Application_Id_Here',
      }
    },
    {
      popUp: !isIE,
      consentScopes: [
        'user.read',
        'openid',
        'profile',
      ],
      protectedResourceMap: [
        ['https://graph.microsoft.com/v1.0/me', ['user.read']]
      ]
    })
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MsalInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

当您使用此流程获取访问令牌时,您会发现令牌是 ver: "1.0",因为令牌的版本是由资源(在您的情况下是 Microsoft Graph)决定的,而不是客户,参考原因here:


测试:

https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize?
client_id=xxxxx
&response_type=token
&redirect_uri=http://localhost/myapp/permissions
&scope=email openid profile
&response_mode=fragment
&state=12345
&nonce=678910