Search code examples
access-tokenazure-ad-b2cazure-ad-msal

Access token is null in Msal response-Azure AD B2C


I have an SPA Vue.js app, using msal.js to connect Azure AD B2C to get the Id,access token and use the access token for furthur call to my APIs(which is a .net core webApi). So far I was using built in user flow and now I have to change to custom policy. I figured I don't get access token through custom policy. Access token is null in msal response.

onToken:(ctx,error,response) => ...

I have defined my default scope in the SPA and Azure. If I run the custom policy in Azure AD b2c and set the Access token and select jwt.msas reply Url, I am able to see the access token in response. So I think there is nothing wrong with the custom policy. So it looks like I need to do some additional call with msal to Azure and get the access token. I couldn't find any good document and I already tried AquireToken in msal, and it didn't work. I am not sure if I have to set the response type in the initial msal authentication call to 'code, id-token' or 'id-token token'? Or how to do that? and If not what can I do to get the access token as I am in front-end and using implicit flow.


Solution

  • Response type should be or include token.

    This simple code is all you need to get your access token (response type token is implicit):

    function authCallback(error, response) {
        // Handle redirect response
    }
    
    userAgentApplication.handleRedirectCallback(authCallback);
    
    const accessTokenRequest: AuthenticationParameters = {
        scopes: ["{your b2c exposed api scope}"]
    }
    
    userAgentApplication.acquireTokenSilent(accessTokenRequest).then(function (accessTokenResponse) {
        // Acquire token silent success
        // Call API with token
        let accessToken = accessTokenResponse.accessToken;
    }).catch(function (error) {
        //Acquire token silent failure, and send an interactive request
        console.log(error);
        if (error.errorMessage.indexOf("interaction_required") !== -1) {
            userAgentApplication.acquireTokenRedirect(accessTokenRequest);
        }
    });