Skip to content

MsalGuard - Support RBAC with CanActivateFn #5804

Open
@dirthsj

Description

@dirthsj

Core Library

MSAL.js v2 (@azure/msal-browser)

Wrapper Library

MSAL Angular (@azure/msal-angular)

Public or Confidential Client?

Public

Description

Starting with Angular 14.2, you can pass a CanActivateFn to the canActivate array. This function can contain inject calls and can be created dynamically at runtime very easily.

I have created a wrapper for MsalGuard which implements RBAC using this feature, but it would be nice if it was officially supported. Here is a sample of my implementation:

  static forRole(role: string): CanActivateFn {
    return (route, state) => {
      const msalGuard = inject(MsalGuard);
      const authGuardBase = new RoleAuthGuard(msalGuard, role);
      return authGuardBase.canActivate(route, state);
    }
  }

RoleAuthGuard handles waiting for MsalGuard to succeed, then acquires a token from Msal using acquireTokenSilent and verifies the idTokenClaims contain the specified role. This could be much more efficient if MsalGuard could verify the idTokenClaims internally.

Example Usage:

const routes: Routes = [
  {
    component: AdminComponent,
    path: 'admin',
    canActivate: [RoleAuthGuard.forRole('Administrator')],
  }
}

PS: Also of note, class and InjectionToken guards and resolvers, such as the current MsalGuard impelmentation, are scheduled for removal in Angular 17. CanActivateFn is the replacement. I would appreciate it if this feature was included when the necessary changes to support Angular 17 are made.

Source

External (Customer)

Metadata

Metadata

Assignees

Labels

enhancementEnhancement to an existing feature or behavior.featureFeature requests.msal-angularRelated to @azure/msal-angular packagemsal-browserRelated to msal-browser packagepublic-clientIssues regarding PublicClientApplications

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions