ASP.NET Web API : Correct way to return a 401/unauthorised response

后端 未结 8 1188
后悔当初
后悔当初 2020-11-28 08:41

I have an MVC webapi site that uses OAuth/token authentication to authenticate requests. All the relevant controllers have the right attributes, and authentication is workin

相关标签:
8条回答
  • 2020-11-28 09:24

    You should be throwing a HttpResponseException from your API method, not HttpException:

    throw new HttpResponseException(HttpStatusCode.Unauthorized);
    

    Or, if you want to supply a custom message:

    var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
    throw new HttpResponseException(msg);
    
    0 讨论(0)
  • 2020-11-28 09:25

    Just return the following:

    return Unauthorized();
    
    0 讨论(0)
  • 2020-11-28 09:31

    In .Net Core You can use

    return new ForbidResult();
    

    instead of

    return Unauthorized();
    

    which has the advantage to redirecting to the default unauthorized page (Account/AccessDenied) rather than giving a straight 401

    to change the default location modify your startup.cs

    services.AddAuthentication(options =>...)
                .AddOpenIdConnect(options =>...)
                .AddCookie(options =>
                {
                    options.AccessDeniedPath = "/path/unauthorized";
    
                })
    
    0 讨论(0)
  • 2020-11-28 09:33

    To add to an existing answer in ASP.NET Core >= 1.0 you can

    return Unauthorized();
    
    return Unauthorized(object value);
    

    To pass info to the client you can do a call like this:

    return Unauthorized(new { Ok = false, Code = Constants.INVALID_CREDENTIALS, ...});
    

    On the client besides the 401 response you will have the passed data too. For example on most clients you can await response.json() to get it.

    0 讨论(0)
  • 2020-11-28 09:37

    You get a 500 response code because you're throwing an exception (the HttpException) which indicates some kind of server error, this is the wrong approach.

    Just set the response status code .e.g

    Response.StatusCode = (int)HttpStatusCode.Unauthorized;
    
    0 讨论(0)
  • 2020-11-28 09:40

    As an alternative to the other answers, you can also use this code if you want to return an IActionResult within an ASP.NET controller.

    ASP.NET

     return Content(HttpStatusCode.Unauthorized, "My error message");
    

    Update: ASP.NET Core

    Above code does not work in ASP.NET Core, you can use one of these instead:

     return StatusCode((int)System.Net.HttpStatusCode.Unauthorized, "My error message");
     return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized, "My error message");
     return StatusCode(401, "My error message");
    

    Apparently the reason phrase is pretty optional (Can an HTTP response omit the Reason-Phrase?)

    0 讨论(0)
提交回复
热议问题