简体   繁体   English

ASP.NET Web API:返回 401/未授权响应的正确方法

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

I have an MVC webapi site that uses OAuth/token authentication to authenticate requests.我有一个 MVC webapi 站点,它使用 OAuth/token 身份验证来验证请求。 All the relevant controllers have the right attributes, and authentication is working ok.所有相关的控制器都具有正确的属性,并且身份验证工作正常。

The problem is that not all of the request can be authorised in the scope of an attribute - some authorisation checks have to be performed in code that is called by controller methods - what is the correct way to return a 401 unauthorised response in this case?问题是并非所有请求都可以在属性范围内获得授权——一些授权检查必须在控制器方法调用的代码中执行——在这种情况下返回 401 未授权响应的正确方法是什么?

I have tried throw new HttpException(401, "Unauthorized access");我试过throw new HttpException(401, "Unauthorized access"); , but when I do this the response status code is 500 and I get also get a stack trace. ,但是当我这样做时,响应状态代码是 500,我也得到了堆栈跟踪。 Even in our logging DelegatingHandler we can see that the response is 500, not 401.即使在我们的日志记录 DelegatingHandler 中,我们也可以看到响应是 500,而不是 401。

You should be throwing a HttpResponseException from your API method, not HttpException :您应该从 API 方法中抛出HttpResponseException ,而不是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);

只需返回以下内容:

return Unauthorized();

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 控制器中返回IActionResult ,也可以使用此代码。

ASP.NET ASP.NET

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

Update: ASP.NET Core更新:ASP.NET 核心

Above code does not work in ASP.NET Core, you can use one of these instead:以上代码在 ASP.NET Core 中不起作用,您可以使用以下代码之一:

 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? )显然,原因短语是可选的( HTTP 响应可以省略原因短语吗?

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.你得到一个 500 响应代码,因为你抛出了一个异常( HttpException ),它表明某种服务器错误,这是错误的方法。

Just set the response status code .eg只需设置响应状态代码 .eg

Response.StatusCode = (int)HttpStatusCode.Unauthorized;

To add to an existing answer in ASP.NET Core >= 1.0 you can要添加到 ASP.NET Core >= 1.0 中的现有答案,您可以

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.在客户端上,除了 401 响应之外,您还将获得传递的数据。 For example on most clients you can await response.json() to get it.例如,在大多数客户端上,您可以await response.json()来获取它。

In .Net Core You can use在 .Net Core 中你可以使用

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这有利于重定向到默认的未经授权的页面(Account/AccessDenied),而不是直接给出 401

to change the default location modify your startup.cs更改默认位置修改您的startup.cs

services.AddAuthentication(options =>...)
            .AddOpenIdConnect(options =>...)
            .AddCookie(options =>
            {
                options.AccessDeniedPath = "/path/unauthorized";

            })

you can use follow code in asp.net core 2.0:您可以在 asp.net core 2.0 中使用以下代码:

public IActionResult index()
{
     return new ContentResult() { Content = "My error message", StatusCode = (int)HttpStatusCode.Unauthorized };
}

You also follow this code:您还可以遵循以下代码:

var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
      Content = new StringContent("Users doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
      StatusCode = HttpStatusCode.NotFound
 }
 throw new HttpResponseException(response);

Make sure that the lines order in "Startup.cs" is like this, not vise versa:确保“Startup.cs”中的行顺序是这样的,反之亦然:

app.UseAuthentication(); // the order is important
app.UseAuthorization();

That was what cased the issue in my case.这就是我的问题所在。

Because I found this post as best match.因为我发现这篇文章是最匹配的。 For a ASP.NET Core Web Api the ReturnType ContentResult is a good choice:对于 ASP.NET Core Web Api,ReturnType ContentResult 是一个不错的选择:

[HttpPost]
[Route("api/my-controller")]
public async ContentResult Index([FromBody] MyRequestType request)
{
  


    if (!authenticate(request.User,request.Password)
    {
       return new ContentResult() { StatusCode = StatusCodes.Status401Unauthorized };
    }

    //Process request
    var myReturnObject = await processRequest(request);

    string errString = System.Text.Json.JsonSerializer.Serialize(myReturnObject);
    return new ContentResult()
    {
        Content = errString,
        StatusCode = StatusCodes.Status200OK,
    };

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 ASP.NET Web API 中立即返回 HTTP 响应 - Return HTTP Response immediately in ASP.NET Web API 如何使ASP.Net Core Web API Identity在未经授权的情况下返回401 - How to make ASP.Net Core Web API Identity return a 401 on unauthorized 使用 Windows 身份验证的 Asp.net 核心 Web api - Cors 请求未经授权 - Asp.net core web api using windows authentication - Cors request unauthorised ASP.NET Web API JWT间歇性401错误 - ASP.NET Web API JWT intermittent 401 errors 添加凭据标头时的ASP.NET Web API 401 - ASP.NET Web API 401 when adding credential header Exchange Web Service API和401未经授权但成功 - Exchange Web Service API and 401 unauthorised but succeeding Web api asp.net中的返回值 - return value in web api asp.net 3次登录尝试后出现401未经授权的访问错误,如何重新加载页面? 在asp.net - How to reload page after 3 login attempts with 401 unauthorised access error? in asp.net ASP.Net Core 3.1 WEB API - Controller 方法不返回正确的 Z0ECD11C1D7A287401F814A8 - ASP.Net Core 3.1 WEB API - Controller method doesn't return correct JSON 在ASP.Net Web API 2上支持多种授权属性的正确方法 - Correct way to support multiple authorization attributes on ASP.Net Web API 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM