如何使用ADAL / OpenId在azure AAD中获取当前用户?

时间:2015-05-25 18:28:06

标签: c# azure adal

我有以下代码来获取上下文令牌。

public class UserProfileController : Controller
    {
        private static string azureAdGraphApiEndPoint = ConfigurationManager.AppSettings["ida:AzureAdGraphApiEndPoint"];
        private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private static string appKey = ConfigurationManager.AppSettings["ida:AppKey"];

        public async Task<ActionResult> GetPropertiesForUser()
        {
            Uri serviceRoot = new Uri(azureAdGraphApiEndPoint);
            var token = await GetAppTokenAsync();

            ActiveDirectoryClient adClient = new ActiveDirectoryClient(
             serviceRoot,
             async () => await GetAppTokenAsync());
            string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            Microsoft.Azure.ActiveDirectory.GraphClient.Application app = (Microsoft.Azure.ActiveDirectory.GraphClient.Application)adClient.Applications.Where(
                a => a.AppId == clientId).ExecuteSingleAsync().Result;
            if (app == null)
            {
                throw new ApplicationException("Unable to get a reference to application in Azure AD.");
            }

            string requestUrl = string.Format("https://graph.windows.net/mysaasapp.onmicrosoft.com/users/{0}?api-version=1.5", token);

            HttpClient hc = new HttpClient();
            hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(
                "Bearer", token);

            HttpResponseMessage hrm = await hc.GetAsync(new Uri(requestUrl));

            if (hrm.IsSuccessStatusCode)
            {
                string jsonresult = await hrm.Content.ReadAsStringAsync();
                return View("TestRestCall", new SuccessViewModel
                {
                    Name = "The Title",
                    Message = "The message",
                    JSON = jsonresult.ToJson()
                });
            }
            else
            {
                return View();
            }
        }

        private static async Task<string> GetAppTokenAsync()
        {
            string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
            string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
            string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
            string tenant = ConfigurationManager.AppSettings["ida:Tenant"];
            string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
            string azureAdGraphApiEndPoint = ConfigurationManager.AppSettings["ida:AzureAdGraphApiEndPoint"];
            // This is the resource ID of the AAD Graph API.  We'll need this to request a token to call the Graph API.
            string graphResourceId = ConfigurationManager.AppSettings["ida:GraphResourceId"];

            string Authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant);

            // Instantiate an AuthenticationContext for my directory (see authString above).
            AuthenticationContext authenticationContext = new AuthenticationContext(Authority, false);

            // Create a ClientCredential that will be used for authentication.
            // This is where the Client ID and Key/Secret from the Azure Management Portal is used.
            ClientCredential clientCred = new ClientCredential(clientId, appKey);

            // Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
            // using the Client ID and Key/Secret as credentials.
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(graphResourceId, clientCred);

            // Return the access token.
            return authenticationResult.AccessToken;
        }

但是我需要用当前的用户电子邮件替换令牌,但还没找到。

1 个答案:

答案 0 :(得分:3)

首先,如果我误解了这个问题,请原谅我。

如果您想从索赔中获取用户的电子邮件,我认为根据您的租户可能会有所不同。对我来说,我可以在“upn”和“unique name”下找到我的电子邮件。

以此为例;

string email= ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;

这会给我发电子邮件,或者为空。

就我而言,如果我像你一样使用“http://schemas.microsoft.com/identity/claims/objectidentifier”“,它会在我的租户Active Directory中返回一个唯一标识我的GUID。

你有没有检查过你的声明,看看那里有什么?