首页 文章

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

提问于
浏览
16

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

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

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

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

[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>();

Update:

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

5 回答

  • 0

    .Net core 2.1 访问JWT bearer tocken

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

    它最终成为配置问题 . AddAuthentication和AddOpenIdConnect之间需要有一个链接,以便将cookie读入 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();
        }
    

    现在填充了访问令牌 .

    注意:我最终把它从这个项目中挖出来Startup.cs

  • 0

    Startup.cs

    public void ConfigureServices(IServiceCollection services)
        {
        ...
         services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
         ...
        }
    

    Controller.cs构造函数

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

    这应该工作

  • 1

    从Azharuddin回答一点点变化

    在Startup方法中注册服务实例

    public void ConfigureServices(IServiceCollection services)
    {
    
     services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
     ...
    }
    

    并在控制器中注入依赖项

    private IHttpContextAccessor _httpContextAccessor;
    public ClientController(IHttpContextAccessor httpContextAccessor)
    {
         _httpContextAccessor = httpContextAccessor;
    }
    

    并在您的操作中检索访问令牌

    [Authorize]
    public async Task<IActionResult> ClientUpdate(ClientModel client)
    {
        var accessToken = _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
    
        ..........//Some other code
        return View();
    }
    
  • 21

    真的,谢谢,这是完美的!

    我有这项工作,但我们的天蓝色租户专注于权威 . 只需用您的租户名称替换******即可 .

    options.Authority = "https://login.microsoftonline.com/******.onmicrosoft.com";
    

    您也可以使用租户ID . 只需在https://login.microsoftonline.com/之后插入您的租户ID

    options.Authority = "https://login.microsoftonline.com/be0be093-****-****-****-5626e83beefc";
    

相关问题