首页 > 解决方案 > Oauth 2.0 如何访问 AuthenticationProperties 中保存的访问令牌

问题描述

我提前为我的英语道歉。

我必须开发一个使用 Oauth 2.0 在外部站点上进行身份验证的 Web api。接下来,我必须使用返回给我的访问令牌将请求发送到同一站点。我正在使用 github API 进行测试。

这是启动类:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
         // This lambda determines whether user consent for non-essential cookies is needed for a given request.
         options.CheckConsentNeeded = context => true;
         options.MinimumSameSitePolicy = SameSiteMode.None;
    });


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddAuthentication(options =>
    {
         options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
         options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
         options.DefaultChallengeScheme = "GitHub";
    })
    .AddCookie()
    .AddOAuth("GitHub", options =>
    {
        options.ClientId = Configuration["GitHub:ClientId"];
        options.ClientSecret = Configuration["GitHub:ClientSecret"];
        options.CallbackPath = new PathString("/signin-github");

        options.AuthorizationEndpoint = "https://github.com/login/oauth/authorize";
        options.TokenEndpoint = "https://github.com/login/oauth/access_token";
        options.UserInformationEndpoint = "https://api.github.com/user";

        options.SaveTokens = true;

        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
        options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
        options.ClaimActions.MapJsonKey("urn:github:login", "login");
        options.ClaimActions.MapJsonKey("urn:github:url", "html_url");
        options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url");

        options.Events = new OAuthEvents              
        {
            OnCreatingTicket = async context =>
            {
                Console.WriteLine("This is the access Token: " + context.AccessToken);
                var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted);
                response.EnsureSuccessStatusCode();

                var user = JObject.Parse(await response.Content.ReadAsStringAsync());

                context.RunClaimActions(user);
            }
        };


    });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication(); 

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });
    }
}

有了这个:

        options.SaveTokens = true;

令牌应该保存在 AuthenticationProperties 中,但在我的控制器中,我不知道如何访问令牌以便将其传递到请求的标头中。

我唯一发现的是一个过时的方法,就是这样:

var authenticateInfo = await HttpContext.Authentication.GetAuthenticateInfoAsync("Bearer");
string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];

但我有这个错误:

No authentication handler is configured to authenticate for the scheme: Bearer

这是我的打字客户端

public class Service
{
    public HttpClient Client { get;  }

    public Service(HttpClient client)
    {
        var token = GetTokenAsync();

        client.DefaultRequestHeaders.Add("Authorization", "");    //here I have to pass the access token

        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");

        Client = client;
    }

    public async Task<string> GetTokenAsync()
    {
        //I want the access token returned to me

        return token;
    }

}

标签: c#oauth-2.0asp.net-core-webapiaccess-token

解决方案


您可以通过以下方式获取访问令牌:

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

推荐阅读