提供者的详细信息与Azure活动目录令牌

时间:2016-08-12 11:08:50

标签: c# azure-mobile-services

我使用google和microsoft帐户进行azure Active Directory身份验证。在从AAD进行身份验证后,它返回访问令牌。我们正在传递请求标头。在令牌的基础上,我想获得当前提供商的详细信息。这可以通过标题中的标记帮助在web api代码中获取用户的详细信息吗?

1 个答案:

答案 0 :(得分:3)

您可以从/.auth/me端点获取各种信息。由于您使用的是带有Xamarin Forms的Azure移动应用程序:

为声明设置模型:

using System.Collections.Generic;
using Newtonsoft.Json;

namespace TaskList.Models
{
    public class AppServiceIdentity
    {
        [JsonProperty(PropertyName = "id_token")]
        public string IdToken { get; set; }

        [JsonProperty(PropertyName = "provider_name")]
        public string ProviderName { get; set; }

        [JsonProperty(PropertyName = "user_id")]
        public string UserId { get; set; }

        [JsonProperty(PropertyName = "user_claims")]
        public List<UserClaim> UserClaims { get; set; }
    }

    public class UserClaim
    {
        [JsonProperty(PropertyName = "typ")]
        public string Type { get; set; }

        [JsonProperty(PropertyName = "val")]
        public string Value { get; set; }
    }
}

然后使用以下内容获取声明:

List<AppServiceIdentity> identities = null;

public async Task<AppServiceIdentity> GetIdentityAsync()
{
    if (client.CurrentUser == null || client.CurrentUser?.MobileServiceAuthenticationToken == null)
    {
        throw new InvalidOperationException("Not Authenticated");
    }

    if (identities == null)
    {
        identities = await client.InvokeApiAsync<List<AppServiceIdentity>>("/.auth/me");
    }

    if (identities.Count > 0)
        return identities[0];
    return null;
}

提供者和提供者令牌位于模型中。提供程序返回的任何声明都在UserClaims对象中,您可以使用LINQ进行访问。例如,要检索名称:

var identity = await service.GetIdentityAsync();
if (identity != null) {
    name = identity.UserClaims.FirstOrDefault(c => c.Type.Equals("name")).Value;
}

您可以从我的图书部分获取更多信息:https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter2/authorization/

相关问题