我有一个用.NETCore编写的Web API应用程序,我想要做的就是使用操作过滤器拦截请求,然后从标头中验证JWT令牌。我写了一个如下所示的ActionFilter:
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
namespace Applciation.ActionFilters
{
public class AuthorizeJWT: ActionFilterAttribute, IActionFilter
{
void IActionFilter.OnActionExecuting(ActionExecutingContext context)
{
var jwt = context.HttpContext.Request.Headers["JWT"];
try
{
var json = new JwtBuilder()
.WithSecret(File.ReadLines("").ToList().First())
.MustVerifySignature()
.Decode(jwt);
var tokenDetails = JsonConvert.DeserializeObject<dynamic>(json);
}
catch (TokenExpiredException)
{
throw new Exception("Token is expired");
}
catch (SignatureVerificationException)
{
throw new Exception("Token signature invalid");
}
catch(Exception ex)
{
throw new Exception("Token has been tempered with");
}
}
}
}
现在,我在服务配置中添加了动作过滤器,如下所示:
services.AddScoped<AuthorizeJWT>();
并如下所示装饰我的控制器:
[AuthorizeJWT]
public virtual async Task<IActionResult> Ceate([FromBody]CreateDto,createDto)
{
//method body
}
但是由于某种原因,我的动作筛选器没有被调用。配置中缺少什么吗?
最佳答案
ActionFilter
的定义不正确。您只需要从ActionFilterAttribute
类派生而不是从接口IActionFilter
派生,因为ActionFilterAttribute类已经实现了该接口。
如果您从继承中删除接口,然后更改您的OnActionExecuting
方法定义以覆盖基类实现,那么一切将按预期工作:
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
namespace Applciation.ActionFilters
{
public class AuthorizeJWT: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var jwt = context.HttpContext.Request.Headers["JWT"];
try
{
var json = new JwtBuilder()
.WithSecret(File.ReadLines("").ToList().First())
.MustVerifySignature()
.Decode(jwt);
var tokenDetails = JsonConvert.DeserializeObject<dynamic>(json);
}
catch (TokenExpiredException)
{
throw new Exception("Token is expired");
}
catch (SignatureVerificationException)
{
throw new Exception("Token signature invalid");
}
catch(Exception ex)
{
throw new Exception("Token has been tempered with");
}
}
}
}
关于c# - Action 筛选器未称为WebAPI/.net Core,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50690773/