简体   繁体   中英

Azure AD authentication issue with asp.net core

How to get ID token and access token in a Azure AD authorization for the ASP.NET Core web app ? I'd like to pass that token to the client application for API access. Is that proper scenario?

You can use MSAL library sign in users and request the tokens that are used to access an API that's protected by Azure AD.

The following code snippet shows how to sign in users:

// Add scopes for the id token to be used at Microsoft identity platform endpoints.
const loginRequest = {
    scopes: ["api://your_api_applicationid/.default"],
};

myMSALObj.loginPopup(loginRequest)
    .then((loginResponse) => {
    //Login Success callback code here
}).catch(function (error) {
    console.log(error);
});

Get a user token silently

const tokenRequest = {
    scopes: ["api://your_api_applicationid/.default"]
};

    myMSALObj.acquireTokenSilent(tokenRequest)
        .then((tokenResponse) => {
            // Callback code here
            console.log(tokenResponse.accessToken);
        }).catch((error) => {
            console.log(error);
        });

Reference:

Quickstart: Sign in users and get an access token in a JavaScript SPA

You can use Implicit flow for spa application which runs in the context of a web browser which cannot manage client secrets securely . Here is code sample for React .

In MSAL, you can get access tokens for the APIs your app needs to call using the acquireTokenSilent method which makes a silent request(without prompting the user with UI) to Azure AD to obtain an access token. The Azure AD service then returns an access token containing the user consented scopes to allow your app to securely call the API. You can refer to codes from AuthProvider.js .

Another more secure way is to use Authorization Code Flow with PKCE . MSAL.js 2.0.0 supports that flow and is Alpha Released currently , see document here for more details .

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