Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Get Access Token for Azure AD Identity

I try to get an access token for an identity to get data from all users profiles. I'm using OpenID connect to authenticate the user, in which I succeeded. I'm also able to get an access token, but it is not valid.

The code I'm using: To authenticate:

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

To acquire an access token for 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();
    }

But when I execute the request, I get:

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

What am I doing wrong?

like image 557
Mr. Martini Avatar asked Oct 14 '25 14:10

Mr. Martini


1 Answers

I had the same issue. Use following code which I have used to get the Access Token from Azure AD. Just Login to your Azure portal and find your Tenant ID and Client ID and paste it to the following code. It works perfectly for me.

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

    }
}
like image 62
Chamila Maddumage Avatar answered Oct 17 '25 03:10

Chamila Maddumage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!