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 |1 Answer
Reset to default 1You 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
版权声明:本文标题:angular - accessing generated access token when using msal - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736309634a1934087.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
acquireTokenSilent()
to which you can give the scope for your API. – juunas Commented Nov 21, 2024 at 15:18