Search code examples
azureazure-active-directoryaccess-token

Obtain Azure Access Token


i am getting this nasty error, i have no idea what i am doing wrong here. My code even looks quite similar to the one found on this blog, but in my case this is not working.

GetAzureAccessToken

Error message

"'authority' Uri should have at least one segment in the path (i.e. https:////...)\r\nParameter name: authority"

public static string GetAzureAccessToken(string clientId, string clientSecret)
    {
        string tenandId = "{tenandId}";
        string loginUri = $"https://login.windows.net/";

        var authCtx =
            new AuthenticationContext(String.Format(CultureInfo.InvariantCulture, loginUri, tenandId));
        var credential = new ClientCredential(clientId: clientId, clientSecret: clientSecret);

        var result = authCtx.AcquireToken(resource: "https://management.core.windows.net/",
            clientCredential: credential);

        if(result == null)
            throw new InvalidOperationException("Failed to aquire token");

        return result.AccessToken;
    }

Solution

  • You define the authority wrong, it should be:

    var authCtx = new AuthenticationContext(loginUri + tenantId);
    

    Also, I guess it does not really matter, but I use https://login.microsoftonline.com/tenant-id as authority usually.