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

时间:2018-10-17 06:53:35

标签: c# azure azure-active-directory openid-connect adal

我尝试获取用于身份的访问令牌,以从所有用户个人资料中获取数据。我正在使用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" } } }

我在做什么错了?

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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

    }
}