1

我正在开发用户通过 Steam 登录的 ASP.NET Core Web API。

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

    // ...
}

现在我正在使用 cookie,身份验证和授权都可以正常工作。但我想使用 JWT。如果我简单地替换AddCookieAddJwtBearer我得到以下异常The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler' which cannot be used for SignInAsync

在这个github issue中,它说我需要一个 OpenID Connect 服务器,但我不明白为什么,因为如果我想自己编写 JWT 逻辑,我可以在 open id 回调中生成令牌并将其返回给用户. 还是我错过了什么?

4

1 回答 1

1

请参阅@KévinChalet 对以下代码的安全问题的评论。

调用 HandleResponseSteamAuthenticationOptions.Events.OnTicketReceived以便它不会调用SignInAsync并且能够自己进行重定向以加入 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;
            };
        });

    // ...
}

当挑战 Steam 后认证成功时,会生成一个 jwt 并将用户重定向到{ReturnUri}?token={jwt}.

于 2020-01-28T23:27:41.840 回答