c# - 如何使用 ADAL/OpenId 获取 azure AAD 中的当前用户?

标签 c# azure adal

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

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

但是我需要用当前用户电子邮件替换 token ,但还没有找到方法。

最佳答案

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

如果您想从 claim 中获取用户的电子邮件,我认为这可能会有所不同,具体取决于您的租户。对我来说,我可以在“upn”和“唯一名称”下找到我的电子邮件。

举个例子;

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 "",它返回一个 GUID,在我的租户 Active Directory 中唯一标识我。

您是否检查过您的 claim ,看看里面有什么?

关于c# - 如何使用 ADAL/OpenId 获取 azure AAD 中的当前用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444096/

相关文章:

azure - Azure VM 上的 IIS/HTTP 端点(非经典)

azure - 在返回的 JWT 中找不到 approles

javascript - 找不到模块 : Error: Cannot resolve module 'fs' in

c# - 如何使用 Oracle Managed Data Access c# 进行批量插入

c# - 如何发出 GET 请求并将结果解析到列表

C# 线程传递整数参数传递错误数字

azure - 一个Azure移动服务NotificationHub将推送通知发送到两个不同的IOS应用程序

c# - 无法让 XmlDocument.SelectNodes 检索我的任何节点?

azure - 间歇性出现 404 错误, "Owner resource does not exist"

asp.net - 使用 Azure AD 和 WebAPI 进行服务到服务身份验证