Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 403 Forbidden response as IActionResult in ASP.NET Core

I would like to return a 403 Forbidden to the client when trying to perform an invalid operation. What is the method I need to use?

I searched over the internet but I found only these for MVC 5:

If the return type for your web api method is HttpResponseMessage then you need to use the below code:

return Request.CreateErrorResponse(HttpStatusCode.Forbidden, "RFID is disabled for this site.");
Or  if the return type for your web api method is IHttpActionResult then you need to use the below code

return StatusCode(HttpStatusCode.Forbidden,"RFID is disabled for this site.");

How to return 403 for IActionResult type:

public IActionResult Put(string userid, [FromBody]Setting setting)
 {
    var result = _SettingsRepository.Update(userid, setting);
    if (result == true)
    {
       return Ok(201);
    }
    else
    {
       return BadRequest();
    }
 }
like image 706
wandermonk Avatar asked Jul 14 '17 06:07

wandermonk


People also ask

What does IActionResult return?

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.

Is ASP NET core 403 forbidden access is denied?

This means that an ASP.NET application deployed inside the root folder already has Read and Execute permissions to its application folders. However, if your ASP.NET application needs to use files or folders in other locations, you must specifically enable access.

What is the meaning of HTTP status code 403?

The HTTP 403 Forbidden response status code indicates that the server understands the request but refuses to authorize it. This status is similar to 401 , but for the 403 Forbidden status code re-authenticating makes no difference.


4 Answers

When you want to respond with a HTTP 403 status and allow ASP.NET Core's authentication logic to handle the response with its forbidden handling logic (can be configured in your Startup class, and may cause a redirect to another page), use:

return Forbid();

(same applies to Unauthorized())


When you want to respond with a HTTP 403 status code from an API and do not want the ASP.NET Core authentication logic to perform any redirect or other action, use:

return StatusCode(403);

// or with developer-friendly type
return StatusCode(StatusCodes.Status403Forbidden);

// or as an api-friendly error response
return Problem(
    type: "/docs/errors/forbidden",
    title: "Authenticated user is not authorized.",
    detail: $"User '{user}' must have the Admin role.",
    statusCode: StatusCodes.Status403Forbidden,
    instance: HttpContext.Request.Path
);

The latter example produces a client error response.

like image 174
Bart Verkoeijen Avatar answered Oct 30 '22 08:10

Bart Verkoeijen


Alternative to MstfAsan's answer is to use:

return Forbid();

It is a method on the controller base class that does the same thing.

Or

return StatusCode(403);

If you want to return a message, then you must use StatusCode.

like image 42
juunas Avatar answered Oct 30 '22 08:10

juunas


You can use return new ForbidResult(); Class declaration is

public class ForbidResult : ActionResult, IActionResult

For more spesific usages visit https://learn.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.forbidresult

like image 38
MstfAsan Avatar answered Oct 30 '22 08:10

MstfAsan


Simply you can use ObjectResult to return a custom response with a status code.

See the syntax,

return new ObjectResult("Message") {StatusCode = YOUR_STATUS_CODE };

Note - You can pass an object also,

return new ObjectResult(your_model) {StatusCode = YOUR_STATUS_CODE };

Example:

public async Task<IActionResult> Post([FromBody] SomeData _data)
{
     // do your stuff

    // return forbidden with custom message
    return new ObjectResult("Forbidden") { StatusCode = 403};
}
like image 32
shalitha senanayaka Avatar answered Oct 30 '22 08:10

shalitha senanayaka