如何记录“未经授权”(401)响应

时间:2019-01-11 17:51:29

标签: c# asp.net-core

我正在使用JWT令牌进行身份验证

services.AddAuthentication(options =>
{
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
    .AddJwtBearer(jwtOptions =>
    {
        jwtOptions.TokenValidationParameters = tokenValidationParameters;
    });

在我的控制器中,[Authorize]属性用于确保呼叫者需要进行身份验证。这很好。

但是:如果未经授权的用户发出请求,他将收到401响应。我可以以某种方式“中断”此响应并记录进行了未经授权的呼叫吗?

编辑

建议添加我已经这样做的“异常中间件”,但是未经授权的调用不会引发异常...

services.AddMvc()
    .AddMvcOptions(options =>
    {
        // Order is important! A request will run from top to bottom through each filter.
        options.Filters.Add(typeof(MyExceptionFilterAttribute));
    });

和属性:

public class MyExceptionFilterAttribute : ExceptionFilterAttribute
{
    /// <summary>
    /// ctor
    /// </summary>
    public MyExceptionFilterAttribute()
    {

    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    public override void OnException(ExceptionContext context)
    {


        ApplicationLogger.LogError("Bad request", context.Exception);
    }
}

1 个答案:

答案 0 :(得分:2)

如何?

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
{
    // ...

    app.Use(async (context, next) =>
    {
        await next();

        if (context.Response.StatusCode == (int)System.Net.HttpStatusCode.Unauthorized)
        {
            logger.LogWarning("Unauthorized request");
        }
    });

    app.UseAuthentication();

    // ...
}