There's a small but significant difference between 401 and 403 response codes. Both are related to authentication and authorization.
Let's start by defining the difference between authentication and authorization. In most systems, you can't have authorization without authentication, but you can have authentication without authorization. However, some systems may implement basic authorization (e.g., based on IP addresses) without explicit authentication.
Authentication (401)
Authentication is like your key card or building access badge. This tells the system you have the credentials to enter. That's all it does. Authentication can be seen as binary - black and white/yes or no. Does this person with these credentials have access to this system? If the answer is no, the response code will typically be 401.
A 401 response code tells the caller that the credentials supplied were not valid, or that credentials are required but weren't provided. In most cases, this person is not allowed through the door. Authentication also tells the system who you are, like a badge with your name and photo. The badge is your identity.
Authorization (403)
Authorization happens after a system has authenticated the requestor. Via a token, user/group, user id + password or some other authorization mechanism, in the end the caller has passed validation and the system knows who you are. With authorization, the system determines what you have access to. Your badge gets you in the door, but what group you belong to determines which rooms you can enter. If you try to access a method or route that your user does not have rights to - your role - the system will return a 403 response code. This means your credentials are valid; however, you do not have access to the resource you are requesting.
To summarize
- 401 error code: Typically returned when a system doesn't know who you are, you've used invalid credentials, or when credentials are required but not provided.
- 403 error code: Indicates the system knows who you are but you don't have access to the requested resource.
Note that while this explanation covers common scenarios, authentication and authorization can be more complex in some systems, potentially involving multi-factor authentication or other advanced methods.