OAuth 2.0如何访问保存在AuthenticationProperties中的访问令牌 [英] Oauth 2.0 How to access the access token saved in AuthenticationProperties

查看:55
本文介绍了OAuth 2.0如何访问保存在AuthenticationProperties中的访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提前为我的英语道歉。

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

这是Startup类:

// 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;
    }

}

推荐答案

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

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

这篇关于OAuth 2.0如何访问保存在AuthenticationProperties中的访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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