How to get access token from HttpContext in .Net core 2.0
In Controller, the token can be retrieved by reading Request.Headers
dictionary:
var accessToken = Request.Headers["Authorization"];
At other classes where HttpContext is not available, there token can be retrieved using HttpContextAccessor
after injecting into services collection (
A little change from Azharuddin answer)
Register the service instance in Startup method like
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
...
}
And inject the dependency in your controller like
private IHttpContextAccessor _httpContextAccessor;
public ClientController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
And retrieve the access token in your action like
[Authorize]
public async Task<IActionResult> ClientUpdate(ClientModel client)
{
var accessToken = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
..........//Some other code
return View();
}
.Net core 2.1 to access JWT bearer token
var accessToken = Request.Headers[HeaderNames.Authorization];
It ended up being a configuration issue. There needs to be a link between AddAuthentication and AddOpenIdConnect in order for it to read the cookie into the headers.
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddAuthentication(options =>
{
options.DefaultScheme = "Cookies";
options.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookies")
.AddOpenIdConnect("oidc", options =>
{
options.SignInScheme = "Cookies";
options.Authority = "http://localhost:5000";
options.RequireHttpsMetadata = false;
options.ClientId = "testclient";
options.ClientSecret = "secret";
options.ResponseType = "code id_token";
options.SaveTokens = true;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add("testapi");
options.Scope.Add("offline_access");
});
Controller
[Authorize]
public async Task<IActionResult> Index()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
return View();
}
Access token is now populated.
Note: I ended up digging it out of this project Startup.cs
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;