ADAL v3:如何使用UserPasswordCredential进行身份验证?

时间:2016-11-08 23:52:31

标签: adal

ADAL v3有UserPasswordCredential类,但我找不到有效的实现。没有AcquireToken重载,它接受UserPasswordCredential或UserCredential类型。在ADAL v3中执行用户名和密码流的正确方法是什么?这段特殊代码使用完整的.Net 4.5。

2 个答案:

答案 0 :(得分:4)

如果您使用客户端应用程序进行开发,可以参考以下代码获取令牌:

string authority = "https://login.microsoftonline.com/xxxx.onmicrosoft.com";
string resrouce = "https://graph.windows.net";
string clientId = "";
string userName = "";
string password = "";
UserPasswordCredential userPasswordCredential = new UserPasswordCredential(userName,password);
AuthenticationContext authContext = new AuthenticationContext(authority);
var token= authContext.AcquireTokenAsync(resrouce,clientId, userPasswordCredential).Result.AccessToken;

如果您使用Web应用程序进行开发(这不是常见情况),ADAL V3中没有这样的方法来支持此方案。作为解决方法,您可以自己构建请求。以下是供您参考的示例:

POST: https://login.microsoftonline.com/xxxxx.onmicrosoft.com/oauth2/token

Content-Type: application/x-www-form-urlencoded
resource={resource}&client_id={clientId}&grant_type=password&username={userName}&password={password}&scope=openid&client_secret={clientSecret}

答案 1 :(得分:4)

详细说明接受答案的第二部分,这是一个发出POST请求的实现:

    From SettingHelper: public static string GetAuthorityEndpoint(string azuretenantId) => $"https://login.microsoftonline.com/{azuretenantId}/";

    private static async Task<OAuthResult> AuthenticateAsync(string resource = "https://yourAzureADProtectedResource.url/")
    {
        var oauthEndpoint = new Uri(new Uri(SettingsHelper.GetAuthorityEndpoint("your AAD Tenent ID")), "oauth2/token");

        using (var client = new HttpClient())
        {
            var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("resource", resource),
                new KeyValuePair<string, string>("client_id", "your AAD App Id"),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("username", "your.user@yourtenent.url"),
                new KeyValuePair<string, string>("password", "your password"),
                new KeyValuePair<string, string>("scope", "openid"),
                new KeyValuePair<string, string>("client_secret", "an access key for your AAD App"),
            }));

            var content = await result.Content.ReadAsStringAsync();
            var authResult = JsonConvert.DeserializeObject<OAuthResult>(content);
            return authResult;
        }
    }

    class OAuthResult
    {
        public string Token_Type { get; set; }
        public string Scope { get; set; }
        public int Expires_In { get; set; }
        public int Ext_Expires_In { get; set; }
        public int Expires_On { get; set; }
        public int Not_Before { get; set; }
        public Uri Resource { get; set; }
        public string Access_Token { get; set; }
    }

然后您可以继续使用Auth结果:

    private async Task<HttpClient> GetHttpClientWithAzureADAuthentication()
    {
        OAuthResult authResult;
        try
        {
            authResult = await AuthenticateAsync();
            var httpClient = GetHttpClient();
            httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {authResult.Access_Token}");

            return httpClient;
        }
        catch (Exception e)
        {
            Debug.WriteLine(e);
            throw;
        }
    }
相关问题