When to Return a 401 vs 403 HTTP Response

There are two side of the security coin: authentication and authorization.

Authentication answers the question of who (a principal) is making the request to a given endpoint. Authorization is what determines if the principal is actually is allowed to do what they are trying to do.

If authentication fails, a 401 Unauthorized response should be returned. Authentication can fail for a lot of reasons: bad password, an expired API token, something in the application changed, etc. For example, a user changing their password often invalidates any oauth tokens issued on behalf of that user. Those invalidated tokens would start returning 401 responses.

If authorization fails, a 403 Forbidden response should be returned. This is the web application saying, “yes, I see who you are, but you can’t do that.” An OAuth resource server could see an incoming access token and user behind the token. The user itself may be able to access the requested endpoint, but the access token is missing a scope. That’s a 403 response.