.net 刚接触JWT时,需要了解使用什么中间件来验证JWT令牌

vbkedwbf  于 2023-03-04  发布在  .NET
关注(0)|答案(2)|浏览(115)

有一个.net framework API,当前正在使用SimpleAuthorizationServerProvider。现在要求我们使用OpenId和JWT来提供API授权。JWT令牌将通过授权服务器创建,只需在API端验证颁发者、受众、client_id。难以找到正确的中间件来注入验证令牌逻辑。
已尝试以下操作:

public void ConfigureAuth(IAppBuilder app)
    {
        var OAuthOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
            Provider = new JWTAuthorizationServerProvider() //new SimpleAuthorizationServerProvider()
        };

        //app.UseOAuthBearerTokens(OAuthOptions);
        app.UseOAuthAuthorizationServer(OAuthOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

        OAuthBearerAuthenticationOptions options = new OAuthBearerAuthenticationOptions();
        
        app.Map("/api", api =>
        {
            
            api.UseOAuthBearerAuthentication(options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = false,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Jwt:Issuer"],
                ValidAudience = Configuration["Jwt:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) 
            };

        });

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);
    }

TokenValidationParameters不是OAuthBearerAuthenticationOptions的一部分。我猜这不是正确的身份验证方法。

z31licg0

z31licg01#

JwtSecurityTokenHandler类可用于验证JWT。该类具有TokenValidationParameters,可将其作为参数发送到ValidateToken方法。

toe95027

toe950272#

您应该使用JwtBearer处理程序来验证ASP.NET核心应用程序中的JWT标记。
样本代码

services.AddAuthentication("token")
    .AddJwtBearer("token", options =>
    {
        options.Authority = "https://identityservice.mysecure.nu";
        //...
    });

/...

app.UseAuthentication();
app.UseAuthorization();

JwtBearer做什么?它转换、验证传入的令牌,并基于令牌创建一个User对象。

如果您需要排除JwtBearer的故障,那么我在这里有一篇关于此问题的博客文章Troubleshooting JwtBearer authentication problems in ASP.NET Core

相关问题