Skip to content

Commit

Permalink
more performant tokens lookup
Browse files Browse the repository at this point in the history
  • Loading branch information
themsaid committed May 4, 2020
1 parent 51e401e commit 5ce9e05
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/HasApiTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function createToken(string $name, array $abilities = ['*'])
'abilities' => $abilities,
]);

return new NewAccessToken($token, $plainTextToken);
return new NewAccessToken($token, $token->id.'|'.$plainTextToken);
}

/**
Expand Down
10 changes: 9 additions & 1 deletion src/PersonalAccessToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,15 @@ public function tokenable()
*/
public static function findToken($token)
{
return static::where('token', hash('sha256', $token))->first();
if (! strpos($token, '|')) {
return static::where('token', hash('sha256', $token))->first();
}

[$id, $token] = explode('|', $token);

if ($instance = static::find($id)) {
return $instance->token == hash('sha256', $token) ? $instance : null;
}
}

/**
Expand Down
9 changes: 8 additions & 1 deletion tests/HasApiTokensTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,16 @@ public function test_tokens_can_be_created()

$newToken = $class->createToken('test', ['foo']);

[$id, $token] = explode('|', $newToken->plainTextToken);

$this->assertEquals(
$newToken->accessToken->token,
hash('sha256', $newToken->plainTextToken)
hash('sha256', $token)
);

$this->assertEquals(
$newToken->accessToken->id,
$id
);
}

Expand Down

1 comment on commit 5ce9e05

@Nitwix
Copy link

@Nitwix Nitwix commented on 5ce9e05 Apr 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this is quite an old commit, but I'm interested in the security implications of adding an id to access tokens. My concern is in particular with the ability for an adversary to learn when users connect, if the id's are sequential.
For example, an attacker can make a script to request a new token each second: if the id increased by 1 since the last request, no one connected in the interval. If the id increased by more than one, one or more users connected in the interval. This can be automated to enable an adversary to track user activity on a site. Are there countermeasures in place? Wouldn't random id's have the same performance benefits, without the security drawback?
I would appreciate any insights about this.

Please sign in to comment.