I'm trying to use ASP.Net Core 2.2 with OAuth authentication. To use OAuth I use the AddOAuth method in the public void ConfigureServices(IServiceCollection services)in Startup.cs:
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";
});
The problem is, that when the middleware tries to get an authorization code by using the TokenEndpoint, I receive a HTTP 401 because the provider expects a basic authentication header at this endpoint.
My question is, how can I tell the middleware to add a basic auth header to the TokenEndpoint request?
@Kirk Larkin Thanks for posting the link, this helped me alot to came up with a solution!
I created a DelegateHandler which adds a basic authentication header if the request is send to the TokenEndpoint:
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);
}
}
This DelegateHandler is used in the ConfigureService method:
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);
//...
});
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With