0

I am getting 401 error when trying to make secure call from Angular to web api end-point. I got Bearer token authenticated via Active Directory / MSAL. I am calling API from testAPI1() method in below code...

enter image description here

import { Component, OnInit } from '@angular/core';
import { MsalService } from '@azure/msal-angular';
import { AuthenticationResult } from '@azure/msal-common';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';

 @Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.scss']
 })

export class AppComponent implements OnInit{

  title = 'HandHeldClientADAuth';
  isAuthenticated = false;
  token: string = "";
  idToken: string = "";
  tokenType: string = "";
  idTokenClaims: string = "";
  authority: string = "";
  state: string | undefined = "";
  expiresOn: Date | null = new Date();
  uniqueId: string = "";
  username: string | undefined;

 constructor(private msalServices: MsalService, private http: HttpClient,){
 
 }

ngOnInit(){
this.msalServices.instance.handleRedirectPromise().then(
  res => {
    if(res!=null && res.accessToken !=null){
      this.msalServices.instance.setActiveAccount(res.account);
      this.token = res.accessToken;
      this.authority = res.authority;
      this.idToken = res.idToken;
      var idTokenClaims = res.idTokenClaims;
      this.tokenType = res.tokenType;
      this.state = res.state;
      this.expiresOn = res.expiresOn;
      this.uniqueId = res.uniqueId;
      this.username = res.account?.username;

      console.log("TokenClaims ::"+idTokenClaims);

    }
  }
 )
}

isLoggedIn(): boolean{
 return this.msalServices.instance.getActiveAccount() != null
}

loginRedirect(){
 this.msalServices.loginRedirect();
}

logout(){
 this.msalServices.logout();
}

testAPI1(){
    var t2 = this.token;
    const myheaders = new HttpHeaders({
        'Content-Type': 'application/json; charset=utf-8',
        'Authorization': 'Bearer '+ this.token,
        'Access-Control-Allow-Origin':'*'
    });

 console.log("calling Web APIs App 'GetSecureMessage' API ...");
 this.http.get('https://localhost:44362/v2/Site/GetSecureMessage', {headers: myheaders})
    .subscribe((data)=>{
        console.warn(data);
    })
 }
}
K.Z
  • 5,201
  • 25
  • 104
  • 240
  • https will not work with localhost – mikegross Oct 04 '21 at 15:48
  • I guess you already did, but change console.log("calling Web APIs App 'GetSecureMessage' API ...") for console.log("calling Web APIs App 'GetSecureMessage' API ... - Token", this.token ); and see if you actually have value in this.token when you invoke testAPI1(). – Juan Vicente Berzosa Tejero Oct 04 '21 at 15:55
  • I do have the token and can see in debug ... – K.Z Oct 04 '21 at 15:58
  • Another try: try just with: 'Content-Type': 'application/json; 'Authorization': `Bearer ${this.token}`, (NOTE: I'm going to put as answer because here it doesn't show well). – Juan Vicente Berzosa Tejero Oct 04 '21 at 15:59
  • 401 error means unauthorized, so first, if you removed the [Authorize] attrbute, can your request reached the api? If ok, let check the bearer token if have the correct scp cliam for delegate permission or roles claim for application permission(as you mentioned in the question, here should be a delegate permission token). Just decode the jwt token. – Tiny Wang Oct 11 '21 at 08:31

1 Answers1

0

Another try. Try just with:


   const myheaders = new HttpHeaders({
        'Content-Type': 'application/json,
        'Authorization': `Bearer ${this.token}`,
   });

If it doesn't work, try to modify directly the API call in the ANGULAR INTERCEPTOR, as I described HERE

If none of these solutions work, maybe you have some problem with the part of the authorisation, and not in the HTTP call.

  • I am not getting luck... I am using Hotmail email address to get token from AD where AD is register Web API application as Single Tenant ... does it makes difference? I have also register multi-Tenant application both web api and client as trying alternative but no luck. In this approach my console application fail to authenticate that worked on secret If I register application on AD as multi Tenant – K.Z Oct 05 '21 at 11:50