Without using auth middleware, how to get user id by token?

You don't need the auth middleware to be enabled. You can use auth('api')->user() to get the active user. It will be null if no token is present.


To get the user by the token, you need to understand what the token is.

The token is broken up into three base64 encoded parts: the header, the payload, and the signature, separated by periods. In your case, since you're just wanting to find the user, you just need the header

To get the header, you can do something like this:

// break up the string to get just the token
$auth_header = explode(' ', $access_token);
$token = $auth_header[1];
// break up the token into its three parts
$token_parts = explode('.', $token);
$token_header = $token_parts[0];

// base64 decode to get a json string
$token_header_json = base64_decode($token_header);
// you'll get this with the provided token:
// {"typ":"JWT","alg":"RS256","jti":"9fdb0dc4382f2833ce2d3993c670fafb5a7e7b88ada85f490abb90ac211802720a0fc7392c3f2e7c"}

// then convert the json to an array
$token_header_array = json_decode($token_header_json, true);

Once you have this, you can find the user's token in the jti key:

$user_token = $token_header_array['jti'];

And you can get the user using that:

// find the user ID from the oauth access token table
// based on the token we just got
$user_id = DB::table('oauth_access_tokens')->where('id', $user_token)->value('user_id');

// then retrieve the user from it's primary key
$user = User::findOrFail($user_id);

More info on jwt's.