Return HTTP 403 using Authorize attribute in ASP.Net Core

前端 未结 2 2091
忘掉有多难
忘掉有多难 2021-02-05 04:11

When using ASP.Net WebAPI, I used to have a custom Authorize attribute I would use to return either an HTTP 403 or 401 depending on the situation. e.g.

2条回答
  •  我寻月下人不归
    2021-02-05 05:07

    I ended up doing it with middleware:

    public class AuthorizeCorrectlyMiddleware
    {
        readonly RequestDelegate next;
    
        public AuthorizeCorrectlyMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            await next(context);
    
            if (context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
            {
                if (context.User.Identity.IsAuthenticated)
                {
                    //the user is authenticated, yet we are returning a 401
                    //let's return a 403 instead
                    context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                }
            }
        }
    }
    

    which should be registered in Startup.Configure before calling app.UseMvc().

提交回复
热议问题