Get a token in a web app that calls web APIs - Microsoft identity platform (2024)

Microsoft.Identity.Web adds extension methods that provide convenience services for calling Microsoft Graph or a downstream web API. These methods are explained in detail in A web app that calls web APIs: Call an API. With these helper methods, you don't need to manually acquire a token.

If, however, you do want to manually acquire a token, the following code shows an example of using Microsoft.Identity.Web to do so in a home controller. It calls Microsoft Graph using the REST API (instead of the Microsoft Graph SDK). Usually, you don't need to get a token, you need to build an Authorization header that you add to your request. To get an authorization header, you inject the IAuthorizationHeaderProvider service by dependency injection in your controller's constructor (or your page constructor if you use Blazor), and you use it in your controller actions. This interface has methods that produce a string containing the protocol (Bearer, Pop, ...) and a token. To get an authorization header to call an API on behalf of the user, use (CreateAuthorizationHeaderForUserAsync). To get an authorization header to call a downstream API on behalf of the application itself, in a daemon scenario, use (CreateAuthorizationHeaderForAppAsync).

The controller methods are protected by an [Authorize] attribute that ensures only authenticated users can use the web app.

[Authorize]public class HomeController : Controller{ readonly IAuthorizationHeaderProvider authorizationHeaderProvider; public HomeController(IAuthorizationHeaderProvider authorizationHeaderProvider) { this.authorizationHeaderProvider = authorizationHeaderProvider; } // Code for the controller actions (see code below)}

ASP.NET Core makes IAuthorizationHeaderProvider available by dependency injection.

Here's simplified code for the action of the HomeController, which gets a token to call Microsoft Graph:

[AuthorizeForScopes(Scopes = new[] { "user.read" })]public async Task<IActionResult> Profile(){ // Acquire the access token. string[] scopes = new string[]{"user.read"}; string accessToken = await authorizationHeaderProvider.CreateAuthorizationHeaderForUserAsync(scopes); // Use the access token to call a protected web API. HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", accessToken); string json = await client.GetStringAsync(url);}

To better understand the code required for this scenario, see the phase 2 (2-1-Web app Calls Microsoft Graph) step of the ms-identity-aspnetcore-webapp-tutorial tutorial.

The AuthorizeForScopes attribute on top of the controller action (or of the Razor page if you use a Razor template) is provided by Microsoft.Identity.Web. It ensures that the user is asked for consent if needed, and incrementally.

There are other complex variations, such as:

  • Calling several APIs.
  • Processing incremental consent and Conditional Access.

These advanced steps are covered in chapter 3 of the 3-WebApp-multi-APIs tutorial.

Get a token in a web app that calls web APIs - Microsoft identity platform (2024)
Top Articles
How to Write A Privacy Policy For Your Small Business
What Credit Score Do You Start With at 18? | SoFi
WALB Locker Room Report Week 5 2024
neither of the twins was arrested,传说中的800句记7000词
Srtc Tifton Ga
Knoxville Tennessee White Pages
Kem Minnick Playboy
Wordscapes Level 6030
Pangphip Application
Affidea ExpressCare - Affidea Ireland
Imbigswoo
Revitalising marine ecosystems: D-Shape’s innovative 3D-printed reef restoration solution - StartmeupHK
Signs Of a Troubled TIPM
10 Free Employee Handbook Templates in Word & ClickUp
Bowlero (BOWL) Earnings Date and Reports 2024
Craigslist Edmond Oklahoma
Harem In Another World F95
Trivago Sf
Cvs El Salido
Timeforce Choctaw
Why do rebates take so long to process?
Canvasdiscount Black Friday Deals
Mega Personal St Louis
Marion City Wide Garage Sale 2023
Wat is een hickmann?
Weathervane Broken Monorail
Kuttymovies. Com
Worthington Industries Red Jacket
Plasma Donation Racine Wi
Perry Inhofe Mansion
County Cricket Championship, day one - scores, radio commentary & live text
The value of R in SI units is _____?
Microsoftlicentiespecialist.nl - Microcenter - ICT voor het MKB
Tgh Imaging Powered By Tower Wesley Chapel Photos
Bismarck Mandan Mugshots
How to Draw a Sailboat: 7 Steps (with Pictures) - wikiHow
Nba Props Covers
Flipper Zero Delivery Time
Thor Majestic 23A Floor Plan
Promo Code Blackout Bingo 2023
Here's Everything You Need to Know About Baby Ariel
Tropical Smoothie Address
Lesly Center Tiraj Rapid
Stoughton Commuter Rail Schedule
Identogo Manahawkin
Great Clips Virginia Center Commons
Craigslist Indpls Free
March 2023 Wincalendar
Ret Paladin Phase 2 Bis Wotlk
Bones And All Showtimes Near Emagine Canton
Duffield Regional Jail Mugshots 2023
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 5830

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.