如何从.Net core 2.0中的HttpContext获取访问令牌(How to get access token from HttpContext in .Net core 2.0)

编程入门 行业动态 更新时间:2024-10-24 17:33:59
如何从.Net core 2.0中的HttpContext获取访问令牌(How to get access token from HttpContext in .Net core 2.0)

我正在尝试将.Net核心1.1的项目升级到.Net核心2.0,有很多重大变化。 我目前遇到的一个问题是HttpContext.Authentication现在已经过时了。

我一直试图弄清楚如何获取当前请求的Access令牌。 我需要调用另一个需要持有令牌的API。

旧方法.Net核心1.1

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

方法.Net核心2.0

这不起作用因为上下文未注册。

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

无法解析“Microsoft.AspNetCore.Http.HttpContext”类型的服务

我尝试注册它,但这也不起作用

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

在startup.cs中

services.TryAddSingleton<HttpContext, HttpContext>();

更新:

返回null

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

Startup.cs ConfigureServices

如果在初创公司中有什么东西我也不会感到惊讶,因为这里也有很多重大变化。

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配置

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

I am trying to upgrade a project from .Net core 1.1 to .Net core 2.0 there are a lot of breaking changes. One of the things i am currently having an issue with is that HttpContext.Authentication is now obsolete.

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

最满意答案

它最终成为配置问题。 AddAuthentication和AddOpenIdConnect之间需要有一个链接,以便将cookie读入标题。

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

调节器

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

现在填充了访问令牌。

注意:我最终将其从Startup.cs项目中挖掘出来

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

更多推荐

本文发布于:2023-08-04 13:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415938.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:令牌   Net   core   token   access

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!