gpt4 book ai didi

c# - 具有 TokenEndpoint 基本身份验证的 ASP.NET Core OAuth

转载 作者:行者123 更新时间:2023-12-04 01:43:44 24 4
gpt4 key购买 nike

我正在尝试将 ASP.Net Core 2.2 与 OAuth 身份验证结合使用。要使用 OAuth,我在 Startup.cs 中的 public void ConfigureServices(IServiceCollection services) 中使用 AddOAuth 方法:

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

options.AuthorizationEndpoint = "https://api.provider.net/auth/code";
options.TokenEndpoint = "https://api.provider.net/auth/token";
});

问题是,当中间件尝试使用 TokenEndpoint 获取授权码时,我收到了 HTTP 401,因为提供者希望此端点有基本身份验证 header 。

我的问题是,如何告诉中间件向 TokenEndpoint 请求添加基本的身份验证 header ?

最佳答案

@Kirk Larkin 感谢您发布链接,这对我提出解决方案有很大帮助!

我创建了一个 DelegateHandler,如果请求被发送到 TokenEndpoint,它会添加一个基本的身份验证 header :

public class AuthorizingHandler : DelegatingHandler
{
private readonly OAuthOptions _options;
public AuthorizingHandler(HttpMessageHandler inner, OAuthOptions options)
: base(inner)
{
_options = options;
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if(request.RequestUri == new Uri(_options.TokenEndpoint))
{
string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(_options.ClientId + ":" + _options.ClientSecret));

request.Headers.Add("Authorization", $"Basic {credentials}");
}
return base.SendAsync(request, cancellationToken);
}
}

DelegateHandler 用于ConfigureService 方法:

public void ConfigureServices(IServiceCollection services)
{
// ...

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

options.AuthorizationEndpoint = "https://api.provider.net/auth/code";
options.TokenEndpoint = "https://api.provider.net/auth/token";

var innerHandler = new HttpClientHandler();
options.BackchannelHttpHandler = new AuthorizingHandler(innerHandler, options);

//...
});

// ...
}

关于c# - 具有 TokenEndpoint 基本身份验证的 ASP.NET Core OAuth,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56227606/

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