[Azure AD身份的C#获取访问令牌

问题描述 投票:1回答:2

我尝试获取用于身份的访问令牌,以从所有用户个人资料中获取数据。我正在使用OpenID connect来对用户进行身份验证,我在其中成功。我也可以获得访问令牌,但是它无效。

我正在使用的代码:要进行身份验证:

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
        {
            ClientId = AppVar.ClientId,
            ClientSecret = AppVar.ClientSecret,
            Authority = AppVar.AzureADAuthority,
            RedirectUri = "https://localhost:44326/",
            ResponseType = "code id_token",    
            Notifications = new OpenIdConnectAuthenticationNotifications()
            {
                AuthorizationCodeReceived = (context) => {
                    var code = context.Code;
                    ClientCredential credential = new ClientCredential(AppVar.ClientId, AppVar.ClientSecret);
                    string tenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
                    string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
                    ADALTokenCache cache = new ADALTokenCache(signedInUserID);
                    AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.windows.net/{0}", tenantID), cache);
                    AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
                               code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, AppVar.AzureResource);
                    return Task.FromResult(0);
                }
            }
        });

获取https://graph.microsoft.com的访问令牌

public ActionResult Index()
    {
        string usrObjectId = ClaimsPrincipal.Current.FindFirst(AppVar.ClaimTypeObjectIdentifier).Value;
        AuthenticationContext authContext = new AuthenticationContext(AppVar.AzureADAuthority, new ADALTokenCache(usrObjectId));
        ClientCredential credential = new ClientCredential(AppVar.ClientId, AppVar.ClientSecret);
        AuthenticationResult res = authContext.AcquireToken(AppVar.AzureResource, credential);

        var client = new RestClient("https://graph.microsoft.com/v1.0/users/?$select=userPrincipalName,displayName,mobilePhone");
        var request = new RestRequest(Method.GET);



        request.AddHeader("Cache-Control", "no-cache");
        request.AddHeader("Authorization", "Bearer " + res.AccessToken);
        IRestResponse response = client.Execute(request);
        return View();
    }

但是当我执行请求时,我得到:

{ "error": { "code": "InvalidAuthenticationToken", "message": "Access token validation failure.", "innerError": { "request-id": "1cc9e532-bd31-4ca5-8f1d-2d0796883c2e", "date": "2018-10-17T06:50:35" } } }

我在做什么错?

c# azure azure-active-directory openid-connect adal
2个回答
0
投票

查看您的错误,因为它未能通过令牌验证,所以我想这与获取令牌的受众有关。

您正在调用https://graph.microsoft.com端点,因此请确保这是资源的确切值。

特别是在此代码中,确保AppVar.AzureResource获得值https://graph.microsoft.com

AuthenticationResult res = authContext.AcquireToken(AppVar.AzureResource, credential);

var client = new RestClient("https://graph.microsoft.com/v1.0/users/?$select=userPrincipalName,displayName,mobilePhone");
var request = new RestRequest(Method.GET);

0
投票

我有同样的问题。使用下面的代码,我曾使用这些代码从Azure AD获取访问令牌。只需登录到您的Azure门户并找到您的租户ID和客户端ID,然后将其粘贴到以下代码即可。它对我来说非常有效。

namespace TokenGenerator
{
    class Program
    {
        private static string token = string.Empty;

        static void Main(string[] args)
        {
            //Get an authentication access token
            token = GetToken();
        }

        #region Get an authentication access token
        private static string GetToken()
        {
            // TODO: Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 2.21.301221612
            // and add using Microsoft.IdentityModel.Clients.ActiveDirectory

            //The client id that Azure AD created when you registered your client app.
            string clientID = "Your client ID";

            string AuthEndPoint = "https://login.microsoftonline.com/{0}/oauth2/token";
            string TenantId = "Your Tenant ID";

            //RedirectUri you used when you register your app.
            //For a client app, a redirect uri gives Azure AD more details on the application that it will authenticate.
            // You can use this redirect uri for your client app
            string redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";

            //Resource Uri for Power BI API
            string resourceUri = "https://analysis.windows.net/powerbi/api";

            //Get access token:
            // To call a Power BI REST operation, create an instance of AuthenticationContext and call AcquireToken
            // AuthenticationContext is part of the Active Directory Authentication Library NuGet package
            // To install the Active Directory Authentication Library NuGet package in Visual Studio,
            //  run "Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory" from the nuget Package Manager Console.

            // AcquireToken will acquire an Azure access token
            // Call AcquireToken to get an Azure token from Azure Active Directory token issuance endpoint
            string authority = string.Format(CultureInfo.InvariantCulture, AuthEndPoint, TenantId);
            AuthenticationContext authContext = new AuthenticationContext(authority);
            string token = authContext.AcquireTokenAsync(resourceUri, clientID, new Uri(redirectUri), new PlatformParameters(PromptBehavior.Auto)).Result.AccessToken;
            Console.WriteLine(token);
            Console.ReadLine();
            return token;
        }
        #endregion

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.