How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph

How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph

Content Index :

How do request a correct access token in ASP.NET Core for Azure AD to access Microsoft Graph
Tag : chash , By : Shrek Qian
Date : November 24 2020, 03:01 PM

This might help you You need to use OnAuthorizationCodeReceived notification which could be used to acquire access token for microsoft graph api using ADAL/MSAL . Please refer to this blog for ASP.NET Core 2.0 Azure AD Authentication .

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

PHP: 500 Server Error - Request for access token for Microsoft Azure Active Directory Access

Tag : php , By : Cesar Sanz
Date : March 29 2020, 07:55 AM
Does that help The URL should be https://login.microsoftonline.com/{tenant}/oauth2/token.
You have to add the client secret to the request, as well as the resource.

Getting Access Token for Microsoft Graph from asp.net core Authentication web app

Tag : chash , By : tommy
Date : March 29 2020, 07:55 AM
it fixes the issue You can get the access token using ADAL. You can find a pretty good example app here: https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore.
Here is the especially important part where the token is retrieved: https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore/blob/master/WebApp-WebAPI-OpenIdConnect-DotNet/Startup.cs#L100.
    private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
        // Acquire a Token for the Graph API and cache it using ADAL.  In the TodoListController, we'll use the cache to acquire a token to the Todo List API
        string userObjectId = (context.Ticket.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
        ClientCredential clientCred = new ClientCredential(ClientId, ClientSecret);
        AuthenticationContext authContext = new AuthenticationContext(Authority, new NaiveSessionCache(userObjectId, context.HttpContext.Session));
        AuthenticationResult authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
            context.ProtocolMessage.Code, new Uri(context.Properties.Items[OpenIdConnectDefaults.RedirectUriForCodePropertiesKey]), clientCred, GraphResourceId);

        // Notify the OIDC middleware that we already took care of code redemption.
            string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
            AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
            ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
            result = await authContext.AcquireTokenSilentAsync(Startup.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

How can I access Azure Graph AND Microsoft Graph using same OAuth2 token?

Tag : development , By : AnthonyC
Date : March 29 2020, 07:55 AM
Any of those help You cannot literally call both APIs using the same Access Token. Because the access token has a specific audience, and one of the APIs will reject the token when the audience claim does not match its own app id URI.
It seems like what you really want to accomplish is getting two tokens using a single login experience, and you can do this.

.Net Core 2.0 - Get AAD access token to use with Microsoft Graph

Tag : asp.net , By : Hadley
Date : March 29 2020, 07:55 AM
it should still fix some issue I wrote a blog article which shows just how to do that: ASP.NET Core 2.0 Azure AD Authentication
The TL;DR is that you should add a handler like this for when you receive an authorization code from AAD:
.AddOpenIdConnect(opts =>

    opts.Events = new OpenIdConnectEvents
        OnAuthorizationCodeReceived = async ctx =>
            var request = ctx.HttpContext.Request;
            var currentUri = UriHelper.BuildAbsolute(request.Scheme, request.Host, request.PathBase, request.Path);
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

            var distributedCache = ctx.HttpContext.RequestServices.GetRequiredService<IDistributedCache>();
            string userId = ctx.Principal.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

            var cache = new AdalDistributedTokenCache(distributedCache, userId);

            var authContext = new AuthenticationContext(ctx.Options.Authority, cache);

            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(currentUri), credential, ctx.Options.Resource);

            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
public class AdalDistributedTokenCache : TokenCache
    private readonly IDistributedCache _cache;
    private readonly string _userId;

    public AdalDistributedTokenCache(IDistributedCache cache, string userId)
        _cache = cache;
        _userId = userId;
        BeforeAccess = BeforeAccessNotification;
        AfterAccess = AfterAccessNotification;

    private string GetCacheKey()
        return $"{_userId}_TokenCache";

    private void BeforeAccessNotification(TokenCacheNotificationArgs args)

    private void AfterAccessNotification(TokenCacheNotificationArgs args)
        if (HasStateChanged)
            _cache.Set(GetCacheKey(), Serialize(), new DistributedCacheEntryOptions
                AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1)
            HasStateChanged = false;
public class HomeController : Controller
    private static readonly HttpClient Client = new HttpClient();
    private readonly IDistributedCache _cache;
    private readonly IConfiguration _config;

    public HomeController(IDistributedCache cache, IConfiguration config)
        _cache = cache;
        _config = config;

    public IActionResult Index()
        return View();

    public async Task<IActionResult> MsGraph()
        HttpResponseMessage res = await QueryGraphAsync("/me");

        ViewBag.GraphResponse = await res.Content.ReadAsStringAsync();

        return View();

    private async Task<HttpResponseMessage> QueryGraphAsync(string relativeUrl)
        var req = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0" + relativeUrl);

        string accessToken = await GetAccessTokenAsync();
        req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        return await Client.SendAsync(req);

    private async Task<string> GetAccessTokenAsync()
        string authority = _config["Authentication:Authority"];

        string userId = User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        var cache = new AdalDistributedTokenCache(_cache, userId);

        var authContext = new AuthenticationContext(authority, cache);

        string clientId = _config["Authentication:ClientId"];
        string clientSecret = _config["Authentication:ClientSecret"];
        var credential = new ClientCredential(clientId, clientSecret);

        var result = await authContext.AcquireTokenSilentAsync("https://graph.microsoft.com", credential, new UserIdentifier(userId, UserIdentifierType.UniqueId));

        return result.AccessToken;

How to Get a valid access token for my API and Microsoft Graph from Azure Active Directory?

Tag : javascript , By : abuiles
Date : March 29 2020, 07:55 AM
like below fixes the issue Try specifying the scopes as scopes: ["User.Read"] in the acquireTokenSilent() function. Since an access token is only valid for one API. If you need two, call acquireTokenSilent twice with different scopes.
It's okay to specify scopes for two APIs when signing in, but not when getting tokens. A token has an audience that specifies the target API. So you can't use a token for one API against another. And that's why it's only valid for one API.
Related Posts Related QUESTIONS :
  • C# and Arrow Keys
  • How do you resolve a domain name to an IP address with .NET/C#?
  • Should the folders in a solution match the namespace?
  • How can I evaluate C# code dynamically?
  • CSharpCodeProvider Compilation Performance
  • How can I create Prototype Methods (like JavaScript) in C#.Net?
  • DataTable Loop Performance Comparison
  • CSV string handling
  • What is the best way to do unit testing for ASP.NET 2.0 web pages?
  • High availability
  • What to use for Messaging with C#
  • Accessing a Dictionary.Keys Key through a numeric index
  • ConfigurationManager.AppSettings Performance Concerns
  • What Are Some Good .NET Profilers?
  • Is this a good way to determine OS Architecture?
  • How to create a tree-view preferences dialog type of interface in C#?
  • Searching directories for tons of files?
  • Can I have a method returning IEnumerator<T> and use it in a foreach loop?
  • Why can't I have abstract static methods in C#?
  • Displaying ad content from Respose.WriteFile()/ Response.ContentType
  • Convert integers to written numbers
  • Absolute path back to web-relative path
  • How can we generate getters and setters in Visual Studio?
  • Bringing Window to the Front in C# using Win32 API
  • Possible to "spin off" several GUI threads? (Not halting the system at Application.Run)
  • Reading a C/C++ data structure in C# from a byte array
  • How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
  • Setting Objects to Null/Nothing after use in .NET
  • Converting ARBG to RGB with alpha blending
  • Is it better to create Model classes or stick with generic database utility class?
  • Passing enum type to Converter with integer value
  • Pool of objects with objects that are already on the scene in advance
  • StatusBar text fade-out when binding using Caliburn.Micro
  • Queryfilter on ApplicationUser in OnModelCreating in ApplicationDbContext creates StackOverflowException
  • How to get record form a different table based on a value from first table with linq expression?
  • Show data in Grid from returned model
  • Using Attributes to Override Data Model Conventions
  • Basic OOP console calculator, result Error
  • Compositon and Repository pattern
  • Multiple using statements with if condition
  • How do i increase a number by 1 in every line that contain the number 1
  • Add binding to elements that are created in codebehind
  • How to add a column in an existing AspNetUsers table
  • Order a list of elements with another list of doubles
  • How to setup a NuGet package to copy content files to output build directory?
  • In SignalR Core using ChannelWriter: Do I need to call TryComplete twice if there's an exception?
  • C# GetProcessesByName: issue with colon
  • c# wpf | create complex object with user-defined name to Serialize into JSON
  • How can I get a instance of a generic list with reflection?
  • WPF XAML - Design time and visibility of textbox
  • EF Core and MySql query is too slow
  • Getting Registered App Display Name from an App Id
  • How to get all variables from a string
  • Delete entity with all childs connected
  • Azure Build agent cant´t find class library referance
  • Initialize Nested Dictionaries in c#
  • .Net Core Binding
  • Generic event test method, preventing code duplication
  • How do I keep the ellipses in the center when the screen is resized
  • How to require a property using JsonSchema.NET?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com