403 HTTP Status Code in ASP.NET Core Web API

403 HTTP Status Code in ASP.NET Core Web API

In this article, I will discuss How to Return 403 Forbidden HTTP Status Code from the ASP.NET Core Web API Controller Action method with Examples. Please read our previous article discussing How to Return 401 HTTP Status Code in ASP.NET Core Web API with Examples.

403 HTTP Status Code

The 403 HTTP Status Code indicates that the server understands the request but refuses to authorize it. This status is different from a 401 Unauthorized response, which suggests that the client’s request lacks valid authentication credentials. The 403 Forbidden Status Code explicitly indicates that authentication, whether provided or not, will not grant access to the requested resource. Essentially, the server is saying, “I understand your request, but I won’t fulfill it because you don’t have permission to access this content.” The following are the Key points about the 403 Forbidden Status Code:

Unauthorized vs. Forbidden: Unlike the 401 Unauthorized status, which suggests trying again with proper credentials, a 403 Forbidden status indicates that no amount of authentication will change the server’s decision to deny access to the resource.

Use Cases: A server might return a 403 status for various reasons, such as:

  • The client’s credentials do not grant them access to the requested resource.
  • The request is understood but not allowed for security reasons or due to the server’s access control policies.
  • Specific resources are intentionally hidden for certain users, regardless of authentication.

Resolution Steps: When encountering a 403 Forbidden error, users can attempt several steps to resolve the issue, including:

  • Verifying the URL is correct and does not contain typos.
  • Check if the resource is intended to be publicly accessible and whether you have permission to access it.
  • Clearing the browser’s cache and cookies as outdated or corrupt stored data can sometimes cause this error.
  • Contact the website or server administrator for information on why access is denied or to request access if it’s a resource you should legitimately be able to access.
How to Return 403 HTTP Status Code in ASP.NET Core Web API?

To return a 403 HTTP status code in an ASP.NET Core Web API, you can use the StatusCode method available in the ControllerBase class. This class provides a convenient way to return an HTTP status code along with an optional payload. A 403 Status Code indicates that the server understood the request but refuses to authorize it. This is commonly used in scenarios where authentication is successful, but the authenticated user does not have permission to perform the requested action.

Here’s how you can return a 403 Forbidden response in an ASP.NET Core Web API controller method without data:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetResource()
        {
            // Your logic here
            // For example, check if the user has the right permissions to access the resource
            bool hasPermission = CheckUserPermission();

            if (!hasPermission)
            {
                // User does not have the required permissions
                // Return a 403 Forbidden response
                return StatusCode(StatusCodes.Status403Forbidden);
            }

            // If the user has permission, continue to handle the request
            // For example, return the requested resource
            return Ok("Resource Content Here");
        }

        private bool CheckUserPermission()
        {
            //Logic to Check the User Permission
            return false;
        }
    }
}

In this example, CheckUserPermission() represents a hypothetical method that checks if the current user has the necessary permissions to access a particular resource. If the user does not have the permissions, the method returns a 403 Forbidden status code by calling StatusCode(StatusCodes.Status403Forbidden). Otherwise, it proceeds with handling the request (e.g., returning the requested resource).

Response:

How to Return 403 HTTP Status Code in ASP.NET Core Web API?

Here’s how you can return a 403 Forbidden response in an ASP.NET Core Web API controller action method with data:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetResource()
        {
            // Your logic here
            // For example, check if the user has the right permissions to access the resource
            bool hasPermission = CheckUserPermission();

            if (!hasPermission)
            {
                // User does not have the required permissions
                // Return a 403 Forbidden response
               
                var errorResponse = new 
                {
                    StatusCode = StatusCodes.Status403Forbidden,
                    Message = "Access denied. You do not have permission to access this resource."
                };

                // Use StatusCode method to return 403 Forbidden status and custom data
                return StatusCode(StatusCodes.Status403Forbidden, errorResponse);
            }

            // If the user has permission, continue to handle the request
            // For example, return the requested resource
            return Ok("Resource Content Here");
        }

        private bool CheckUserPermission()
        {
            //Logic to Check the User Permission
            return false;
        }
    }
}
Response:

403 HTTP Status Code in ASP.NET Core Web API

StatusCode Method in ASP.NET Core Web API:

By calling StatusCode(int statusCode, object value), you can specify the HTTP status code and a data object to be serialized into the response body. This method is part of the ControllerBase class, which your controller should inherit when building a Web API. The following are the Benefits of Using the StatusCode Method:

  • Flexibility: Allows you to return a specific HTTP status code and associated data in one response.
  • Clarity: By returning structured data along with the status code, you can provide clients with clear, actionable information regarding the error or status of their request.
  • Convenience: This approach in ASP.NET Core Web API simplifies generating custom responses.
Custom Middleware to Handle 403 Forbidden Error

For scenarios that require custom logic or handling across multiple endpoints, you can implement a middleware that inspects requests and decides whether to proceed or return a 403 response. So, create a class file named CustomAuthorizationMiddleware.cs and copy and paste the following code.

using System.Text.Json;

namespace ReturnTypeAndStatusCodes.Models
{
    public class CustomAuthorizationMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomAuthorizationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            // Custom logic to determine authorization
            bool isAuthorized = CheckUserAuthorization(context);

            if (!isAuthorized)
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
                context.Response.ContentType = "application/json";

                var customResponse = new
                {
                    Code = 403,
                    Message = "Access is denied due to insufficient permissions."
                };

                var responseJson = JsonSerializer.Serialize(customResponse);

                await context.Response.WriteAsync(responseJson);

                return; // Short-circuit the pipeline
            }

            await _next(context);
        }

        private bool CheckUserAuthorization(HttpContext context)
        {
            // Implement your authorization logic here
            // returning false to handle Forbidden scenario
            return false; 
        }
    }
}

In the above example:

  • RequestDelegate _next: A delegate that represents the next middleware in the pipeline. It’s stored in a private read-only field and initialized through the constructor.
  • Constructor: The constructor takes a RequestDelegate parameter representing the next piece of middleware in the pipeline. This delegate is assigned to the _next field.
  • Invoke Method: This is the method that’s called when the middleware executes. It receives the HttpContext as a parameter, which provides information about the incoming request.
  • CheckUserAuthorization: A method called to determine if the request is authorized. This would contain your custom authorization logic.
  • If isAuthorized is false, it sets the response’s status code to 403 Forbidden and specifies the content type as JSON.
  • Custom Response: A custom response object is created and serialized into JSON. This JSON string is then written to the response body. This step customizes the error message sent to the client, providing more detail about why the request was denied.
  • return: The return statement ensures that the middleware pipeline execution stops here for unauthorized requests, preventing further processing by subsequent middleware components or the request from reaching the resource it was intended for.
  • _next(context): If the request is authorized, the middleware passes control to the next component in the pipeline by calling _next with the context.
  • CheckUserAuthorization Method: This method represents where you would implement your specific authorization logic, such as checking if the user has the required permissions or roles. For demonstration purposes, it simply returns false.
Registration the Middleware

After defining the middleware, you must register it within your application’s request pipeline, typically in the Program.cs file, using the UseMiddleware extension method. This ensures that your middleware is executed for every incoming HTTP request. So, please add the following statement to the Program.cs class file:

app.UseMiddleware<CustomAuthorizationMiddleware>();

Note: Ensure your custom middleware is registered at the appropriate point in the middleware pipeline. It should be registered before any middleware that might terminate the pipeline prematurely for unauthenticated or unauthorized requests.

Modifying the Employee Controller:

Next, modify the Employee Controller as follows:

using Microsoft.AspNetCore.Mvc;

namespace ReturnTypeAndStatusCodes.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        [HttpGet]
        public IActionResult GetResource()
        {
            return Ok("Resource Content Here");
        }
    }
}

Now, run the application and access the above endpoint, and you should get the following 403 Forbidden response:

Custom Middleware to Handle 403 Forbidden Error

When Should We Return 403 HTTP Status Code in ASP.NET Core Web API?

In ASP.NET Core Web API, a 403 HTTP status code, defined as “Forbidden,” should be returned when the server understands the request but refuses to authorize it. This refusal does not depend on whether the request lacks valid authentication credentials; instead, it indicates that the authenticated user does not have permission to access the requested resource. It’s a scenario where authentication has succeeded, the server knows who the user is, but the user does not have the necessary permissions for the action they are requesting. Here are specific scenarios where returning a 403 HTTP status code is appropriate:

  • User Role Restrictions: If your application has role-based access control, and the current user’s role does not grant them permission to access a particular resource or perform a certain action, you should return a 403 Status Code. For example, if only administrators can access certain endpoints, and a non-administrator user attempts to access one of these, a 403 response would be appropriate.
  • Resource Ownership: In situations where users are only allowed to access or modify resources they own or have explicit permissions for, attempts by a user to access resources owned by another user without permission should result in a 403 response. For example, a user is trying to edit another user’s profile without having the right to do so.
  • Access Control Lists (ACLs): If your application uses more granular access control lists for managing permissions, and a user attempts to access a resource for which they are not on the ACL, you should return a 403 Status Code.

In the next article, I will discuss How to Return a 404 HTTP Status Code in ASP.NET Core Web API with Examples. In this article, I try to explain How to Return 403 Forbidden HTTP Status Code in ASP.NET Core Web API with Examples, and I hope you enjoy this article on “403 Forbidden HTTP Status Code in the ASP.NET Core Web API”.

Leave a Reply

Your email address will not be published. Required fields are marked *