问题描述
我正在尝试将一个项目从 .Net core 1.1 升级到 .Net core 2.0,有很多重大变化.
我目前遇到的问题之一是 HttpContext.Authentication
现在已过时.
我一直在尝试弄清楚如何获取当前请求的访问令牌.我需要调用另一个需要不记名令牌的 API.
旧方法 .Net 核心 1.1
[授权]公共异步任务ClientUpdate(ClientModel 客户端){var accessToken = await HttpContext.Authentication.GetTokenAsync(access_token");返回视图();}
方法 .Net 核心 2.0
这不起作用,因为上下文未注册.
[授权]公共异步任务ClientUpdate(ClientModel 客户端){var accessToken = await context.HttpContext.GetTokenAsync(access_token");返回视图();}
无法解析Microsoft.AspNetCore.Http.HttpContext"类型的服务
我尝试注册它,但也不起作用
public ConsoleController(IOptions serviceSettings, HttpContext context)
在startup.cs中
services.TryAddSingleton();
更新:
这返回空
var accessToken = await HttpContext.GetTokenAsync("access_token");
Startup.cs 配置服务
如果这是初创公司中的某些事情,我不会感到惊讶,因为这里也有很多突破性的变化.
services.Configure(Configuration.GetSection(ServiceSettings"));//services.TryAddSingleton();services.TryAddSingleton();服务.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 = "秘密";options.ResponseType = "code id_token";options.RequireHttpsMetadata = false;options.GetClaimsFromUserInfoEndpoint = true;});
Startup.cs 配置
loggerFactory.AddDebug();如果 (env.IsDevelopment()){app.UseDeveloperExceptionPage();app.UseBrowserLink();}别的{app.UseExceptionHandler("/Home/Error");}JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();app.UseStaticFiles();app.UseAuthentication();app.UseMvc(routes =>{路线.MapRoute(名称:默认",模板:{controller=Home}/{action=Index}/{id?}");});
它最终成为一个配置问题.AddAuthentication 和 AddOpenIdConnect 之间需要有一个链接才能将 cookie 读入标头.
services.TryAddSingleton();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 = "秘密";options.ResponseType = "code id_token";options.SaveTokens = true;options.GetClaimsFromUserInfoEndpoint = true;options.Scope.Add("testapi");options.Scope.Add("offline_access");});
控制器
[授权]公共异步任务指数(){var accessToken = await HttpContext.GetTokenAsync("access_token");返回视图();}
访问令牌现已填充.
注意:我最终从这个项目中挖掘了它Startup.cs
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();
}
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?}");
});
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
这篇关于如何从 .Net core 2.0 中的 HttpContext 获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!