简体   繁体   中英

How to get access_token from client side for signed in user? using Azure AD B2C hybrid flow

I have a web app on asp.net core 7 that is protected by Azure AD B2C authentication. This part is working and the user is authenticated properly server side, and I can get an access_token server side thanks to AuthorizeForScopes attribute and ITokenAcquisition with GetAuthenticationResultForUserAsync.

Now I need to get an user_access token client side so I can call a web api directly from javascript without the need to re-signing the user.

the client side code is:

 <script src="https://alcdn.msauth.net/browser/2.5.1/js/msal-browser.js"></script> <script type="module"> const msalInstance = new msal.PublicClientApplication({ auth: { clientId: "bbd0f8e1-a81a-43c6-82d8-xxxxxx", authority: "https://login.microsoftonline.com/cfc1d2e8-3626-4dca-9cd7-xxxxxx", }, cache: { cacheLocation: "localStorage", storeAuthStateInCookie: false, } }); const silentRequest = { scopes: ["https://xxxxxx.onmicrosoft.com/webapi/access_as_user"], loginHint: "me@email.com" }; const loginResponse = await msalInstance.ssoSilent(silentRequest); </script>

On Azure AD B2C the config is Manage > Authentication > Implicit grant and hybrid flows > ID tokens (used for implicit and hybrid flows) checked.

Also I think the ssoSilent method is not recommended any more.

When I run the code I have the error Unsafe attempt to initiate navigation for frame with origin xxx to the /authorize endpoint like if it's trying to re-authenticate the user instead of picking it from the cookie.

How can I get the access_token client side from the user logged in server side?

By default, access tokens are not share between applications. You may share the token with your api trough a authenticated (An id token will be required) and secure (trough HTTPS). A better option from a security perspective is to share a refresh token which can be revoked with less setup than access tokens.

Regarding the iframe error, the /authorize endpoint will always be reached as part of any silent. Try Interactive requests with prompt=none as a way to avoid such error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM