Reputation: 1024
I'm developing an ASP.NET Core Web API where the user logins via Steam.
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = SteamAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddSteam(options =>
{
options.Events.OnAuthenticated = ctx => // Create user
});
// ...
}
For now I'm using a cookie and both the authentication and authorization are working fine. But I'd like to use JWTs. If I simply replace AddCookie
by AddJwtBearer
I get the following exception: The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler' which cannot be used for SignInAsync
.
In this github issue, it says that I would need a OpenID Connect server but I don't understand why because if I wanted to write the JWT logic by myself, I could generate the token in the open id callback and return it to the user. Or am I missing something ?
Upvotes: 1
Views: 1233
Reputation: 1024
See @KévinChalet's comment about the security issue with the below code.
Call HandleResponse in SteamAuthenticationOptions.Events.OnTicketReceived
so it doesn't call SignInAsync
and to be able to do the redirect yourself to join the jwt.
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options => // ...)
.AddSteam(options =>
{
options.Events.OnAuthenticated = ctx =>
{
var res = ctx.User[SteamAuthenticationConstants.Parameters.Response];
var players = res[SteamAuthenticationConstants.Parameters.Players];
var player = players.First.ToObject<SteamPlayer>();
// Create user and generate jwt, then
ctx.Request.HttpContext.Items["jwt"] = jwt;
});
options.Events.OnTicketReceived = ctx =>
{
ctx.HandleResponse();
var jwt = ctx.Request.HttpContext.Items["jwt"] as string;
ctx.Response.Redirect(QueryHelpers.AddQueryString(ctx.ReturnUri, "token", jwt));
return Task.CompletedTask;
};
});
// ...
}
When the authentication succeeds after challenging Steam, a jwt is generated and the user is redirected to {ReturnUri}?token={jwt}
.
Upvotes: 2