.NET Core 2.0从HttpContext中获取Access Token的方法及代码

本文主要介绍.NET Core 2.0 Authorize 从HttpContext中获取Token的方法及示例代码。

1、Startup.cs中ConfigureServices配置

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

2、Controller中获取方法

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

3、获取JWT bearer tocken的方法

var accesToken = Request.Headers["Authorization"];

推荐阅读
cjavapy编程之路首页