Can't obtain Azure Oauth V2 access token in C#

188 views Asked by At

I'm trying to obtain an access token from an Azure Web App...C# MVC app. Here is the code I'm using.

    public string GetToken()
    {
        string authority = string.Format(CultureInfo.InvariantCulture, AuthEndPoint, tenantId);

        var credential = new ClientCredential(clientId, clientSecret);
        AuthenticationContext authContext = new AuthenticationContext(authority,true);

        var token = authContext.AcquireTokenAsync(AzureResourceID, credential).Result.AccessToken;
        return token.ToString();
    }

If I strip V2.0 off the end of the authority string, the app will successfully return a V1.0 access token.

How do I get a V2.0 token?

1

There are 1 answers

3
Joy Wang On

You could not get the v2.0 access token from the resource https://database.windows.net, the version of the token is decided by the resource, not the client.

Access tokens are created based on the audience of the token, in your case https://database.windows.net, its related enterprise application is Azure SQL Database whose Application ID is 022907d3-0f1b-48f7-badc-1ba6abab6d66, it is the resource your client request token for, the accessTokenAcceptedVersion of it is null, if the value is null, this parameter defaults to 1, it means you can just get the v1.0 token from this resource, no matter v1.0 or v2.0 endpoint you used in the authority.

See - https://learn.microsoft.com/en-us/azure/active-directory/develop/access-tokens

enter image description here