如何从.Net Core 2.0中的HttpContext获取访问令牌

编程入门 行业动态 更新时间:2024-10-17 21:17:27
本文介绍了如何从.Net Core 2.0中的HttpContext获取访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将项目从.Net core 1.1升级到.Net core 2.0,其中有很多重大更改。我当前遇到的问题之一是 HttpContext.Authentication 现在已过时。

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.

我一直试图弄清楚如何为当前请求获取访问令牌。我需要调用另一个需要承载令牌的API。

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.

旧方法.Net core 1.1

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

方法.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(); }

无法解析 Microsoft类型的服务。 AspNetCore.Http.HttpContext'

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)

在startup.cs

In startup.cs

services.TryAddSingleton<HttpContext, HttpContext>();

更新:

这将返回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 = "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?}"); });

推荐答案

这最终是一个配置问题。

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

现在已填充访问令牌。

Access token is now populated.

注意:我最终从项目 Startup.cs

更多推荐

如何从.Net Core 2.0中的HttpContext获取访问令牌

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

发布评论

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

>www.elefans.com

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