简体   繁体   English

如何使用@azure/msal-angular 获取用户的 AAD 会员资格

[英]How to get user's AAD memberships with @azure/msal-angular

I am using @azure/msal-angular@0.1.4 (Microsoft Authentication Library for Angular) to enable AAD authentication in my Angular 8 application.我正在使用@azure/msal-angular@0.1.4 (用于 Angular 的 Microsoft 身份验证库)在我的 Angular 8 应用程序中启用 AAD 身份验证。 So far, I only have 1 table in my database called emp (id, fname, lname, email) and I am using .net core as my back-end.到目前为止,我的数据库中只有 1 个表,称为 emp(id、fname、lname、email),并且我使用 .net core 作为我的后端。

I did create 2 app registrations one for the my SPA and the other for my API.我确实创建了 2 个应用程序注册,一个用于我的 SPA,另一个用于我的 API。 I already exposed the API and set the User Graph delegate permission in my AD to have user.Read and user.ReadAll.我已经公开了 API 并在我的 AD 中设置了用户图委托权限,以拥有 user.Read 和 user.ReadAll。

My msaluser service looks like this:我的 msaluser 服务如下所示:

import { Injectable } from '@angular/core';
import * as Msal from 'msal';
import { environment } from 'src/environments/environment';
import { Observable } from 'rxjs';

@Injectable()
export class MsaluserService {

  private accessToken: any;
  public clientApplication: Msal.UserAgentApplication = null;
  public clientMembership: Msal.User = null;
  constructor() {
    this.clientApplication = new Msal.UserAgentApplication(
      environment.uiClienId,
      'https://login.microsoftonline.com/' + environment.tenantId,
      this.authCallback,
      {
          storeAuthStateInCookie: true,
      });
  }

  public GetAccessToken(): Observable<any> {
    if (sessionStorage.getItem('msal.idtoken') !== undefined && sessionStorage.getItem('msal.idtoken') != null) {
        this.accessToken = sessionStorage.getItem('msal.idtoken');
    }
    return this.accessToken;
  }

  public authCallback(errorDesc, token, error, tokenType) {
    if (token) {

    } else {
        console.log(error + ':' + errorDesc);
    }
  }

  public getCurrentUserFullName() {
    const user = this.clientApplication.getUser();
    alert(user.name);
  }

  public getCurrentUserEmail() {
    const user = this.clientApplication.getUser();
    alert(user.displayableId)
  }

  public getCurrentUserGroups() {
    // TO BE FETCHED
    // TO BE FETCHED
    // TO BE FETCHED
  }

  public logout() {
    this.clientApplication.logout();
  }

My app module looks like the following我的应用程序模块如下所示

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { environment } from 'src/environments/environment';
import { MsalModule, MsalInterceptor } from '@azure/msal-angular';
import { HttpClientModule, HttpClient, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MsaluserService } from '../_services/msaluser.service';

export const protectedResourceMap: any =
  [
    [environment.baseUrl, environment.scopeUri]
  ];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    MsalModule.forRoot({
      clientID: environment.uiClienId,
      authority: 'https://login.microsoftonline.com/' + environment.tenantId,
      protectedResourceMap: protectedResourceMap,
      redirectUri: environment.redirectUrl
    }),
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    HttpClient,
    MsaluserService,
    { provide: HTTP_INTERCEPTORS, useClass: MsalInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

and my routes has a canActivate: [MsalGuard]我的路线有一个canActivate: [MsalGuard]

in my component.html I am calling these services and everything seem to be working perfectly.在我的 component.html 中,我正在调用这些服务,一切似乎都运行良好。 However, I am trying to get all user's AAD memberships along in the constructor of my msaluser service so I can call this function但是,我试图在我的 msaluser 服务的构造函数中获取所有用户的 AAD 成员资格,以便我可以调用此函数

public getCurrentUserGroups() {
        // TO BE FETCHED
      }

from any component I want when I inject the msaluser service in. Could you show me what code I should write in the getCurrentUserGroups() so I can get the logged in user's AAD memberships?当我注入 msaluser 服务时,来自我想要的任何组件。你能告诉我我应该在getCurrentUserGroups()编写什么代码,以便我可以获得登录用户的 AAD 会员资格吗?

You should know that my dev environment array is like this你应该知道我的开发环境数组是这样的

export const environment = {
  production: false,
  baseUrl:'http://localhost:5000/',
  scopeUri: ['api://<API_APPLICATION_ID>/<NAME>'],
  tenantId: '<TENANT_ID>',
  uiClienId: '<SPA_APPLICATION_ID>',
  redirectUrl: 'http://localhost:4200'
};

Update更新

This is my method that I am trying to call but I am getting unauthorized request althought the accessToken is a valid JWT token这是我尝试调用的方法,但我收到了未经授权的请求,尽管 accessToken 是有效的 JWT 令牌

getCurrentUserGroups(): Observable<any[]> {
      this.httpOptions = {
          headers: new HttpHeaders({
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + this.msalService.GetAccessToken()
          })

      };
      console.log(this.msalService.GetAccessToken());
      return this.http.get('https://graph.microsoft.com/v1.0/users/' + this.msalService.getCurrentUserId() + '/getMemberObjects', this.httpOptions)
          .pipe((response: any) => {
              return response;
          });
    }

Here is a screenshot to the decoded token, it does have the property [hasgroups] so I should be able to use my JWT token to query Microsoft Graph and get the security groups..这是解码令牌的屏幕截图,它确实具有[hasgroups]属性,因此我应该能够使用我的 JWT 令牌来查询 Microsoft Graph 并获取安全组。

在此处输入图片说明

This token I am using to fetch employees info from my back-end repo (.net core) like the following:我用来从我的后端存储库(.net 核心)中获取员工信息的令牌,如下所示:

getEmployees(): Observable<Emp[]> {
      this.httpOptions = {
          headers: new HttpHeaders({
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + this.msalService.GetAccessToken()
          })

      };

      return this.http.get(this.baseUrl + 'emps/', this.httpOptions)
          .pipe((response: any) => {
              return response;
          });
    }

and it is authenticating properly and fetching the data.它正在正确验证并获取数据。

First, your access token is for calling your web API rather than Microsoft Graph.首先,您的访问令牌用于调用您的 Web API,而不是 Microsoft Graph。

And based on your code, the this.accessToken seems to be id token rather than access token.根据您的代码, this.accessToken似乎是 id 令牌而不是访问令牌。

So I'm afraid we cannot modify the getCurrentUserGroups() method directly to implement your requirement.所以恐怕我们不能直接修改getCurrentUserGroups()方法来实现您的要求。

If you want to get the user's AAD Groups, the easiest way is to include Groups claim in your token as instructed here .如果您想获取用户的 AAD 组,最简单的方法是按照此处的说明在您的令牌中包含组声明。

You just need to modify the "groupMembershipClaims" field in application manifest of the Azure AD app:您只需要修改 Azure AD 应用程序清单中的“groupMembershipClaims”字段:

"groupMembershipClaims": "SecurityGroup"

Then the token will contain the Ids of the groups that the use belongs to like below:然后令牌将包含用户所属的组的 ID,如下所示:

{
  "groups": ["{group id}"]
}

In the getCurrentUserGroups() method, try to use something like user.groups .getCurrentUserGroups()方法中,尝试使用类似user.groups东西。

But you can only get the group id here.但是您只能在此处获取组 ID。 So you may need to associate the group id and group name through the configuration file in advance.所以可能需要提前通过配置文件关联组id和组名。

In fact, there is another better way which combines Groups and Roles.事实上,还有另一种更好的方式将 Groups 和 Roles 结合起来。 You can define some app roles and assign the roles to the groups.您可以定义一些应用程序角色并将角色分配给组。 Then the users in the group will have the "roles" claim.然后组中的用户将拥有“角色”声明。

See another similar post here . 在这里查看另一个类似的帖子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有什么方法可以使用@azure/msal-angular 登录用户 azure 订阅 ID? - Is there any way to get logged in user azure subscription Id's using @azure/msal-angular? 登录后如何获取用户名?我正在尝试使用 MSAL (@azure/msal-angular) 进行 Azure 登录 - How to get username after logged in?.I am trying with MSAL (@azure/msal-angular) for Azure Signin 通过 angular 8 中的@azure/msal-angular 库获取 azure 广告用户组 - Get azure ad user group by @azure/msal-angular library in angular 8 @ azure / msal-angular的元数据版本不匹配 - MetaData version mismatch for @azure/msal-angular @azure/msal-angular package 会自动刷新令牌吗? - Does the @azure/msal-angular package automatically refresh token? 您如何使用 MSAL-ANGULAR 读取角色/权限 - How do you read Roles/Permissions using MSAL-ANGULAR 如何侦听 MSAL-Angular 令牌重新身份验证请求? - How do I listen for MSAL-Angular token reauthentiation requests? 如何在 msal-angular 配置中使用 forceRefresh: true? - How to use forceRefresh: true in msal-angular config? 当我使用 Azure static web 应用程序时,为什么 msal-angular `loginPopup` 弹出它自己的页面 - Why does msal-angular `loginPopup` pop ups it's own page when I am using Azure static web app Azure Ad B2C:如何使用 msal-angular 传递在重定向中仍然可用的参数 url - Azure Ad B2C: How to use use msal-angular to pass parameter which still available in redirect url
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM