What is the difference between 401 Unauthorized and 403 Forbidden?

21
When designing an application, it is common for me to be in doubt as to which HTTP code to return when a user does not have access to a given resource: whether it is 401 Unauthorized or whether it is 403 Forbidden .

I wanted a clear explanation of the difference between the two.

    
asked by anonymous 10.02.2015 / 18:36

3 answers

18

401 Unauthorized

It occurs when access to the server resource requires authentication - through the WWW-Authenticate header - and this fails for some reason (lack of credential or invalid credential). The client attempting to connect to the server may try a new request with a more appropriate credential. If a new attempt is made by the same agent with the same credentials the server should provide more relevant information for the user to understand what is happening.

The semantics to be understood here is that valid authentication is lacking. Just this.

403 Forbidden

Occurs when the server refuses to answer the request because of some rule that determined the denial of access. The client should not try again even with credentials because the denial did not occur because of a client failure, or something that could be resolved on the server on its own. The server can give more information if the attempt is made with a HEAD method. This information should describe the reason for the denial. If he does not want to give more information then the error code to be exchanged for 404 Not Found .

The semantics here is that no access authorization was given regardless of what the client provides.

Font .

Although it is not strictly according to the RFC, some servers are configured to only respond to 404 Not Found in any of these cases. This follows the principle of obscurity .

If you consider that HTTP authentication has fallen into disuse in most applications; and that knowing if the resource does not exist or you can not access in the background gives the same; in a pragmatic approach it makes sense to set aside these two error codes.

Of course there may be cases to use the recommendation but you need to know when. Creative and responsible use of codes is not inherently bad.

    
11.02.2015 / 01:31
10

Error 401 refers only to authentication, but does not handle authorization.

Error 401 will be returned when the system is unable to identify the user, while error 403 is encountered when the system can identify the user, but detects that the user is not allowed to do so.

    
10.02.2015 / 18:43
9

401 Unauthorized

It is similar to 403 Forbidden , but we use it specifically when authentication is required and it fails or is not authenticated. It is usually used with HTTP Basic Authentication

403 Forbidden

It may be a restricted area, the request is considered valid, but the server refuses to respond. Other than 401 Unauthorized you will need authentication.

    
10.02.2015 / 18:45