gpt4 book ai didi

c# - Oauth 2.0 如何访问保存在 AuthenticationProperties 中的 access token

转载 作者:行者123 更新时间:2023-12-05 05:05:26 26 4
gpt4 key购买 nike

我提前为我的英语道歉。

我必须开发一个网络 API,它使用 Oauth 2.0 在外部站点上进行 self 验证。接下来,我必须使用返回给我的访问 token 将请求发送到同一站点。我正在使用 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;

token 应保存在 AuthenticationProperties 中,但在我的 Controller 中我不知道如何访问 token 以便将其传递到请求的 header 中。

我唯一找到的是一个过时的方法,那就是:

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

}

最佳答案

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

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

关于c# - Oauth 2.0 如何访问保存在 AuthenticationProperties 中的 access token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60561836/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com