lpotthast / axum-keycloak-auth

Protect axum routes with a JWT emitted by Keycloak.
https://crates.io/crates/axum-keycloak-auth
Apache License 2.0
34 stars 13 forks source link

Incorrect HTTP status codes for authentication and authorization errors #21

Closed Tockra closed 3 months ago

Tockra commented 5 months ago

Our current API implementation returns incorrect HTTP status codes for authentication and authorization errors. This can lead to confusion for API clients and does not adhere to the standard HTTP status code conventions.

The two cases where we need to update the response codes are:

  1. When a user provides no authentication information (e.g., no JWT token or an invalid JWT token), the API currently returns a 400 Bad Request status code. If the token is not valid it returns a 500 status code. However, the appropriate status code for this scenario is 401 Unauthorized.

    According to the HTTP status code specifications (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#401), a 401 Unauthorized status code should be returned when the user does not have valid authentication credentials for the target resource.

  2. When a user is properly authenticated (i.e., they provide a valid JWT token) but lacks the necessary permissions for the specific endpoint, the API currently returns a 401 Unauthorized status code. However, the appropriate status code for this scenario is 403 Forbidden.

    As per the HTTP status code specifications (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#403), a 403 Forbidden status code should be returned when the server understands the request but refuses to authorize it, indicating that the user does not have the required permissions.

Proposed Solution: To address this issue and align our API with the standard HTTP status code conventions, we should:

  1. Update the authentication middleware or the relevant authentication code to return a 401 Unauthorized status code when a user provides no authentication information or an invalid JWT token.

  2. Modify the authorization middleware or the relevant authorization code to return a 403 Forbidden status code when a user is authenticated but does not have the necessary permissions to access the specific endpoint.

By making these changes, our API will provide more accurate and meaningful status codes to the clients, improving the overall developer experience and adhering to the industry standards.

Please let me know if you have any questions or concerns regarding this issue or the proposed solution.