Latest Posts

Friday, May 25, 2018

HTTP Status Codes :: 401 vs 403

HTTP defines status codes, which in turn help design REST API's to be more informative. In other words, REST APIs use the Status-Line part of an HTTP response message to inform clients of their request’s overarching result. 

Refer RFC 2616 for Status-Line syntax.

The world has adopted microservices style architecture at a phenomenal rate. They leverage RESTful API's which use HTTP protocol for communication. In all such calls, the web server and the endpoint at the client returns a status back to the client which can communicate either a success or failure of the API call made.

For any production grade application, security feature has always been its one of the core requirement. There has always been an ongoing discussion around which HTTP status code needs to be put to use for "not authorized" scenarios. The most favorite choices are 401 (unauthorized) and 403 (forbidden)




Lets go through the official definition for these status codes first to help us understand better.

401 UNAUTHORIZED

The request has not been applied because it lacks valid authentication credentials for the target resource.
If the request included authentication credentials, then the 401 response indicates that authorization has been refused for those credentials. The user agent MAY repeat the request with a new or replaced Authorization header field


403 FORBIDDEN

The server understood the request but refuses to authorize it.
A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access.

So in a nutshell,

401 (Unauthorized) - must be used when there is a problem with the client’s credentials.
403 (Forbidden) - should be used to forbid access regardless of authorization state.

No comments:

Post a Comment