Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get access token from HttpContext in .Net core 2.0

I'm trying to upgrade a project from .Net core 1.1 to .Net core 2.0 there's a lot of breaking changes.

One of the things I'm currently having an issue with is that HttpContext.Authentication is now obsolete.

I've been trying to figure out how to get the Access token for the current request. I need to make a call to another API which requires a bearer token.

Old Method .Net core 1.1

[Authorize] public async Task<IActionResult> ClientUpdate(ClientModel client) {     var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");     return View(); } 

Method .Net core 2.0

This is not working becouse context isnt registered.

[Authorize] public async Task<IActionResult> ClientUpdate(ClientModel client) {     var accessToken = await context.HttpContext.GetTokenAsync("access_token");      return View(); } 

Unable to resolve service for type 'Microsoft.AspNetCore.Http.HttpContext'

I tried registering it but that doesnt work either

public ConsoleController(IOptions<ServiceSettings> serviceSettings, HttpContext context)  

In startup.cs

services.TryAddSingleton<HttpContext, HttpContext>(); 

Update:

This returns null

var accessToken = await HttpContext.GetTokenAsync("access_token");   

Startup.cs ConfigureServices

I wouldn't be surprised if it was something in the startup as there were a lot of breaking changes here as well.

services.Configure<ServiceSettings>(Configuration.GetSection("ServiceSettings")); //services.TryAddSingleton<HttpContext, HttpContext>(); services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddMvc(); services.AddAuthentication(options =>         {             options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;             options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;         })         .AddCookie()         .AddOpenIdConnect(options =>         {             options.Authority = "http://localhost:5000";             options.ClientId = "testclient";             options.ClientSecret = "secret";             options.ResponseType = "code id_token";             options.RequireHttpsMetadata = false;             options.GetClaimsFromUserInfoEndpoint = true;         }); 

Startup.cs Configure

loggerFactory.AddDebug(); if (env.IsDevelopment()) {     app.UseDeveloperExceptionPage();     app.UseBrowserLink(); } else {     app.UseExceptionHandler("/Home/Error"); } JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); app.UseStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => {     routes.MapRoute(         name: "default",         template: "{controller=Home}/{action=Index}/{id?}"); }); 
like image 331
DaImTo Avatar asked Apr 11 '18 07:04

DaImTo


People also ask

How use HttpContext current in .NET Core?

ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.

How do I get controller token?

In ASP.NET or ASP.NET Core, calling a web API is done in the controller: Get a token for the web API by using the token cache. To get this token, you call the Microsoft Authentication Library (MSAL) AcquireTokenSilent method (or the equivalent in Microsoft. Identity.

What is HttpContext in .NET Core?

The HttpContext object constructed by the ASP.NET Core web server acts as a container for a single request. It stores the request and response information, such as the properties of request, request-related services, and any data to/from the request or errors, if there are any.


2 Answers

.Net core 2.1 to access JWT bearer token

var accessToken = Request.Headers[HeaderNames.Authorization]; 
like image 121
Chpn Dave Avatar answered Sep 25 '22 13:09

Chpn Dave


if you want the pure token this can help you in .net core 3.1

var _bearer_token = Request.Headers[HeaderNames.Authorization].ToString().Replace("Bearer ", ""); 

and remember you need to add this using

using Microsoft.Net.Http.Headers; 
like image 44
Diego Avatar answered Sep 22 '22 13:09

Diego