Angular 2 SPA Azure Active Directory JWT Issue

℡╲_俬逩灬. 提交于 2019-12-05 20:07:51

Ok, so I have managed to solve this. Basically the solution is the following:

The Angular 2 application must use its configured client id to do the primary authentication with AAD.

So its config is

tenant: '<tenant>',
clientId: '<configured angular 2 client id', 
redirectUri: 'some redirect',
postLogoutRedirectUri: 'some redirect',
cacheLocation: 'localStorage'

And the reason this wasn't working is that once the Angular Client has logged in successfully, it was trying to use this token to access a web api which (and this is the important bit) was on a different machine.

To solve this I called the function acquireToken on the ng2-adal like this:

this.adalService.acquireToken(<client id of target web api>).subscribe(p=>{
       console.log("Acquired token = " + p);

       let headers = new Headers();
        headers.append("Authorization", "Bearer " + p);
        someService.testWebApi(headers).subscribe(res => {
        console.log(res);
      }, (error) => {
        console.log(error);
      });


    }, (error => {
      console.log(error);
    }));

and then the service call worked.. So basically my scenario was that I was trying to do a CORS call to another web api on another machine and hence the token I got to login was not being allowed for making a web api call on another machine.

I have read that a more efficient way of doing this is to store it in the endpoints collection of the config so that when the uri is called for your remote machine, the correct resource endpoint is picked up, but I was unable to get this to work. I hope this helps someone.

Actually, the value of aud in payload should be the Azure AD application's client ID, which your ng2 application acquire access token from. So, if your Web API application on Azure is protected by this AzureAD application, the access token get from ng2 should be able to authorize the request calls against to your Web API.

I have a quick test leverage the NG2 ADAL sample, use the simplest configuration as following:

{
  tenant: '<tenant id>',
  clientId: '<azure ad application client id>', // also use this application to protect the backed services
  redirectUri: window.location.origin + '/',
  postLogoutRedirectUri: window.location.origin + '/'
}

It works fine on my side.

Please double check your configurations and try again.

I had the same problem. In endpoints I had put APP URI ID, replaced it with App ID.

var endpoints = {

    // Map the location of a request to an API to a the identifier of the associated resource
    "https://localhost:44327/": "<Application ID>" // Not APP URI ID
 };

Also enabled CORS for Web API. Followed this: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!