liveBook · Manning

401 unauthorized

As explained in ASP.NET Core in Action, 3e

A 401 Unauthorized response is an HTTP response indicating that authentication is required or has failed for the request.

A 401 Unauthorized response tells an API client that the request is not authenticated. ASP.NET Core returns it when authorization challenges an unauthenticated request, rather than redirecting the client to a login page. section 22.1.1 section 24.2.2

Use the response to distinguish authentication failures from permission failures:

  • 401 means the request lacks valid authentication, such as a missing, malformed, or invalid bearer token. section 24.2.2 section 25.4.1
  • 403 Forbidden means the caller is authenticated but does not have permission to execute the endpoint. section 24.2.2
  • API clients such as SPAs and mobile apps detect the response and decide how to handle it; APIs do not automatically redirect to login pages. section 24.2.2

Diagnosing a bearer-token 401

Send the token in the exact form Authorization: Bearer <token>. If Authorization or Bearer is misspelled, the separating space is missing, or the token is mistyped, the API returns 401. Correct the header and retry the request. section 25.4.1

Listing 22.3 Adding [Authorize] to an action method
public class RecipeApiController : ControllerBase
{
    public IActionResult Get(int id)                       #1
    {
        // method body
    }
 
    [Authorize]                                            #2
    public IActionResult Edit(                             #3
        int id, [FromBody] UpdateRecipeCommand command)    #3
    {
        // method body
    }
}

See how applying [Authorize] to an action causes ASP.NET Core authorization to protect it and challenge unauthenticated requests. section 22.1.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains challenges, API behavior, and bearer-header mistakes, but defers detailed authorization requirements and failure logging.
Examples
Uses a protected Edit action and an Authorization: Bearer <token> request to demonstrate successful correction of a 401.
What it assumes
Assumes familiarity with API requests and authentication, while explaining authorization attributes and bearer-header formatting directly.
What you can do after
Diagnose 401 responses by checking the bearer scheme, spacing, spelling, and token value before retrying an API request.
How it connects
Connects authentication, authorization, Authorize attributes, bearer tokens, JWTs, challenge responses, and 403 Forbidden responses.

Also explained in

Compare how 2 books explain 401 unauthorized →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.