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

标签 c# asp.net-core oauth-2.0

我正在尝试将 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/

相关文章:

c# - 启动并监视终止应用程序? C#

时间:2019-03-17 标签:c#mysqlStoredProcedureInsert返回值

c# - 如何使用 HttpClient 发出 OPTIONS 请求

c# - 依赖注入(inject)的 UserManager 正在处理异步调用 (ASP.NET CORE)

c# - Entity Framework 核心 : many-to-many relationship with same entity

c# - 如何在 ASP.Net Core MVC 模型中使用 C# 解析来自 REST API 的 json 数据并将其显示在 HTML 页面上

oauth-2.0 - Microsoft Graph API 的访问 token 立即过期

c# - 使用枚举和继承的工厂设计模式

PHP Google API - 缺少范围

oauth-2.0 - 当前窗口中 Electron 应用程序中的 OAuth2