admin管理员组

文章数量:1122832

I am having an angular webapp to access protected WebApis. I have created 2 Azure AD apps - one for SPA and another for Webapi. I am using msal v3 for implementing authentication of users. The authentication works fine and the access token obtained for the user is attached by the msal interceptor on making every request to the protected Webapis. I want to access the access token programmatically, how can I do that? Does msal provide any method do so?

I am having an angular webapp to access protected WebApis. I have created 2 Azure AD apps - one for SPA and another for Webapi. I am using msal v3 for implementing authentication of users. The authentication works fine and the access token obtained for the user is attached by the msal interceptor on making every request to the protected Webapis. I want to access the access token programmatically, how can I do that? Does msal provide any method do so?

Share Improve this question asked Nov 21, 2024 at 15:03 Nitesh RatnaparkheNitesh Ratnaparkhe 6397 silver badges21 bronze badges 1
  • The MSAL PublicClientApplication type should have something like acquireTokenSilent() to which you can give the scope for your API. – juunas Commented Nov 21, 2024 at 15:18
Add a comment  | 

1 Answer 1

Reset to default 1

You should be able to simply inject MsalService in any component or service in your app.

First or all, you're going to need to import MSAL modules with:

import { MsalService } from '@azure/msal-angular'
import { AuthenticationResult } from '@azure/msal-browser'

Then, you simply inject MsalService in your constructor:

constructor(private msalService: MsalService) {}

Finally, you'll use the acquireTokenSilent method to acquire your token and do whatever you need with it like so:

this.msalService.instance.acquireTokenSilent({
  scopes: ["api-scopes-you-need"]
}).then((response: AuthenticationResult) => {
   const acquiredToken = response.accessToken;
   // Now it's up to you to do whatever you like with the token here...
)}.catch(error => {
   // Handle errors fetching the token here...
});

You can checkout MSAL documentation here. The docs also delve into the actual method of acquiring the token, which is initially returned from cache if available, or, if not available, a refresh token is requested.

本文标签: angularaccessing generated access token when using msalStack Overflow