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...
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);
})
}
}