获取 Azure 访问令牌

Obtain Azure Access Token

我遇到了这个讨厌的错误,我不知道我在这里做错了什么。我的代码甚至看起来与此博客上的代码非常相似,但就我而言,这是行不通的。

GetAzureAccessToken

错误信息

"'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;
    }

你定义的权限错误,应该是:

var authCtx = new AuthenticationContext(loginUri + tenantId);

此外,我想这并不重要,但我通常使用 https://login.microsoftonline.com/tenant-id 作为权限。