如何从.Net Core 2.0中的HttpContext获取访问令牌 [英] How to get access token from HttpContext in .Net core 2.0

查看:506
本文介绍了如何从.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 = "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?}");
        });


推荐答案

这最终是一个配置问题。

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

控制器

    [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获取访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆