401 vs 403 Status Code

You're building an API and you're trying to decide what status code you should return when a user tries to access a protected resource. Should you return a 401 or a 403 status code?

To put simply:

  • 401 is like saying: "I don't know who you are. Please provide valid credentials."
  • 403 is like saying: "I was able to determine who you are, but you're not allowed to do that particular action."

At it's root, the difference between a 401 and a 403 status code is about authentication versus authorization.

  • Authentication is about determining who a user is using some credential (e.g. username/password, API key, etc.) - that's what the 401 status code is for
  • Authorization is about determining what a user can do (e.g. an admin can delete a post, but a regular user can only edit a post) - that's what the 403 status code is about

401 Unauthorized

Missing authentication token

401 Unauthorized status code illustration
A user requests a protected endpointA token was not provided

403 Forbidden

Invalid permissions to access this resource

403 Forbidden status code illustration
A user requests a protected endpointA valid token was providedUser does not have permission to access this profile

When to use 401 vs 403?

Some examples of when you should use a 401 vs a 403 status code:

401 - Unauthorized403 - Forbidden
No credentials are providedRequest does not contain an API tokenInsufficient permissionsA user with read-only permissions tries to update a resource
Invalid credentials are providedA user provides an invalid API tokenMulti-tenancy violationA user tries to access another user's private messages
Incorrect authentication method is usedA user tries to use Basic Auth when you only allow Bearer AuthSubscription enforcementA user tries to access a premium feature but they are on the free plan