ASP.NET 5 中的 JWT 身份验证使用 OAuthBearerAuthentication

JWT Authentication in ASP.NET 5 using OAuthBearerAuthentication

我正在开发 ASP.NET 5 应用程序,我想使用 JWT 来保护应用程序中的某些端点。目前我们决定由我们(而不是第三方)发布 JWT,因为我们所有的客户都是 'owned' 应用程序,即我们没有 'external' 客户。在示例中,我有一个端点,它使用 jwt-dotnet 库创建和 returns JWT,如下所示(我很欣赏这是一个 基本示例 ,没有过期时间和单个主题索赔等):

...
// include a single subject claim (user id)
var claims = new Dictionary<string, object>() { { "sub", "1234" } };
var key = "EXAMPLE_SECRET_KEY_TO_SIGN_JWT";
var token = JWT.JsonWebToken.Encode(claims, key, JWT.JwtHashAlgorithm.HS256);
...
// return JWT

我可以使用与预期相同的密钥对这个 JWT 进行编码和解码。在我的 Startup.cs 文件中,我使用 Microsoft.AspNet.Authentication.OAuthBearer 中间件来授权我的控制器中指定了 [Authorize] 属性的相关路由。但是,在查看了包括 and 在内的许多帖子后,我似乎找不到如何以相同方式向 OAuth 中间件提供此签名密钥的示例。我的 Startup.cs 文件中的代码如下所示:

public class Startup
{
    public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
    {
        app.UseErrorPage();
        app.UseOAuthBearerAuthentication();
        app.UseMvc();
    }

    ...

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<OAuthBearerAuthenticationOptions>(bearer =>
        {
            bearer.AutomaticAuthentication = true;
            bearer.TokenValidationParameters.ValidAudience = "Example audience";
            bearer.TokenValidationParameters.ValidIssuer = "Example issuer";
            bearer.TokenValidationParameters.ValidateAudience = true;
            bearer.TokenValidationParameters.ValidateIssuer = true;
            bearer.TokenValidationParameters... // how do I set the signing key as a string literal?
        });
        services.AddMvc();
    }
}

我的假设是我应该能够简单地向中间件提供相同的字符串文字密钥,以便它可以验证令牌签名。然而,情况似乎并非如此,因为示例讨论了使用 RSA 密钥或证书而不是提供单个 key/string 文字。

我很感激我可能在这里遗漏了一些东西,或者实际上这可能是错误的方法,我不应该这样做!

编辑:RC2 每晚构建现在原生支持对称密钥:

var key = Convert.FromBase64String("base64-encoded symmetric key");

app.UseJwtBearerAuthentication(options => {
    options.AutomaticAuthenticate = true;
    options.AutomaticChallenge = true;

    options.Authority = Configuration["jwt:authority"];
    options.Audience = Configuration["jwt:audience"];

    options.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(key);
});

你不能,至少在没有一些管道的情况下不能:OAuth2 承载中间件依赖于 IdentityModel 5,它不支持对称密钥,就像你在第一个片段中使用的那样。

当然,最终会支持对称密钥 (https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/250),但同时,建议使用非对称密钥(如 RSA 密钥)。

您也可以自己实现对称密钥支持(参见 https://gist.github.com/sandorfr/4039d540b6b552154522),但使用 RSA 密钥绝对是更好的选择。