我如何获得当前用户在azure AAD,与ADAL/OpenId

本文关键字:AAD ADAL OpenId azure 何获得 用户 | 更新日期: 2023-09-27 17:50:45

我有以下代码来获取上下文标记:

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

然而,我需要用当前用户的电子邮件替换令牌,但还没有找到方法。

我如何获得当前用户在azure AAD,与ADAL/OpenId

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

如果你想从索赔处获得用户的电子邮件,我认为这可能会有所不同,这取决于你的租户。对于我来说,我可以在"upn"answers"唯一名称"下找到我的电子邮件I Claims。

作为一个例子;

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

这将给我我的电子邮件地址,或者null。

在我的例子中,如果我像您一样使用"http://schemas.microsoft.com/identity/claims/objectidentifier",它将返回一个GUID,唯一标识我在我的租户Active Directory中。

你检查过你的索赔单了吗?