Return HTTP status code 401 when auth token is invalid.

Created on 27 October 2022, about 2 years ago
Updated 6 November 2024, about 1 month ago

Problem/Motivation

There is currently no difference between an "access denied" and "token not valid" response, both return a HTTP status code 403. This is problematic because now it's not known wether you don't have access to the endpoint or your auth token is not valid. Both very different cases. This is not a problem when the user never regenerates it auth key, but the problem arrises when the user has generated a new auth key and is stil using the old auth key.

An example of why this is useful (we are using this in our own decoupled application):

  • If we receive a response HTTP status code 403 means we show a "Access denied" status message to the user.
  • If we receive a response HTTP status code 401 we logout the user and require them to get a new auth_key.

Steps to reproduce

  1. Enable key_auth module
  2. Do a request on a resource (REST or JSONAP) with the key_auth authorisation enabled with a invalid/old token.
  3. The request returns a 403 http status code

Proposed resolution

Return a HTTP status code 401 when the token is not valid.

Remaining tasks

User interface changes

API changes

The code below is working for us. I have replaced the "Return NULL;" with a 401 exception. I borrowed this from the Simple OAuth module, that module also does it this way.

  public function authenticate(Request $request) {
    // Get the provided key.
    if ($key = $this->keyAuth->getKey($request)) {
      // Find the linked user.
      if ($user = $this->keyAuth->getUserByKey($key)) {
        // Check access.
        if ($this->keyAuth->access($user)) {
          // Return the user.
          return $user;
        }
      }
    }
    throw new HttpException(
      401,
      'Client authentication failed',
    );
  }

Data model changes

✨ Feature request
Status

Needs review

Version

2.0

Component

Code

Created by

πŸ‡³πŸ‡±Netherlands Sander Wemagine

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024