如何在 WebAPI 的每个请求上将自定义验证应用于 JWT 令牌 ASP.NET

本文关键字:应用于 验证 自定义 JWT 令牌 NET ASP WebAPI 请求 | 更新日期: 2023-09-27 18:35:50

在使用持有者令牌对 Web API 调用进行身份验证时,是否可以向每个请求添加自定义验证?

我正在使用以下配置,并且应用程序已经正确验证了 JWT 令牌。

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    AuthenticationType = "jwt",
    TokenEndpointPath = new PathString("/api/token"),
    AccessTokenFormat = new CustomJwtFormat(),
    Provider = new CustomOAuthProvider(),
});
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    AllowedAudiences = new[] { "all" },
    IssuerSecurityTokenProviders = new[] { new SymmetricKeyIssuerSecurityTokenProvider(Config.JWT_Issuer, Config.JWT_Key) },,
});

现在,由于令牌设置为永不过期,因此我想向使用持有者令牌发出的每个请求添加一个额外的自定义验证步骤,以便我可以验证每个请求的一些其他信息,并在需要时拒绝访问。

在哪里为每个请求添加此验证的正确位置?

如何在 WebAPI 的每个请求上将自定义验证应用于 JWT 令牌 ASP.NET

若要添加其他逻辑来验证或验证传入令牌,有 2 种方法。

1. 使用自定义身份验证提供程序

<小时 />
  1. 编写自定义提供程序,从OAuthBearerAuthenticationProvider继承或实现IOAuthBearerAuthenticationProvider

  2. 在自定义身份验证提供程序中,根据您的目标覆盖/实施ValidateIdentity(...)和/或RequestToken(...),以检查每个请求的传入令牌

根据源代码ValidateIdentity

在创建 System.Security.Claims.ClaimsIdentity 之前调用。使应用程序有机会从其他位置查找标识、调整或拒绝令牌。

根据源代码RequestToken

每次中间件验证请求标识时调用。通过实现此方法,应用程序可以更改或拒绝随请求一起到达的标识。

  1. 通过设置 JwtBearerAuthenticationOptions.Provider 属性来使用自定义提供程序

例:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    // ... other properties here
    Provider = new MyCustomTokenAuthenticationProvider()
    // ... other properties here
});
<小时 />

2. 使用(自定义)令牌处理程序

  1. 编写自定义令牌处理程序,继承自JwtSecurityTokenHandler

  2. 覆盖您想要扩展的任何相关方法(有很多!

  3. 通过设置 JwtBearerAuthenticationOptions.TokenHandler 属性来使用自定义令牌处理程序

例:

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
    // ... other properties here
    TokenHandler = new MyCustomTokenHandler()
    // ... other properties here
});

在.Net Core上,你可以将其添加到JwtBearerOptions

options.Events = new JwtBearerEvents
{
    OnTokenValidated = AdditionalValidation
};

验证函数可能如下所示:

private static Task AdditionalValidation(TokenValidatedContext context)
{
    if ( /* any validation */ ) 
    {
        context.Fail("Failed additional validation");
    }
    return Task.CompletedTask;
}

好消息是,context将包括您需要的所有内容,JWT令牌,HttpContextClaimsPrincipal等。

我会说的最好的方法是编写自定义属性。您需要继承AuthorizeAttribute类并覆盖AuthorizeCore方法,您可以在其中添加自定义验证。

完成后,只需用它装饰您的控制器或方法即可。

https://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute(v=vs.118).aspx

实现示例:

public class MyCustomAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // your validation here
    }
}

使用考试:

[MyCustom]
public ActionResult MyAction()
{
    return View();
}