'Angular 12 - Azure AD Token - Assign Custom Roles

We are using Angular 12 as Front End application & Web API (Asp.net Core 3.1). We have registered both the application in Azure AD & we are able to successfully fetch token from Azure AD.

Needed help on following :-

  1. Need to fetch email address from token
  2. Needs to fetch roles mapped to email address. Roles are stored in SQL Server
  3. If no roles have assigned, needs to redirect user to Unauthorized page
  4. If roles are available, needs to mapped in token so that user can be validated in Web API Controllers / actions

Can someone please guide me on steps for implementing it & also will it be implement on Front End or at Web API level ?

Thanks a lot in advance



Solution 1:[1]

As you are almost there, To achieve the above requirement we can use below sample code to retrieve a user's profile with an HTTP request.

CODE:-

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

const GRAPH_ENDPOINT = 'Enter_the_Graph_Endpoint_Here/v1.0/me';

type ProfileType = {
  givenName?: string,
  surname?: string,
  userPrincipalName?: string,
  id?: string
};

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  profile!: ProfileType;

  constructor(
    private http: HttpClient
  ) { }

  ngOnInit() {
    this.getProfile();
  }

  getProfile() {
    this.http.get(GRAPH_ENDPOINT)
      .subscribe(profile => {
        this.profile = profile;
      });
  }
}

For complete setup please refer this MICROSOFT DOCUMENTATION| Acquire a token in Angular

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AjayKumarGhose-MT