Skip to content

Instantly share code, notes, and snippets.

@smitmartijn
Created April 11, 2023 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smitmartijn/2603a1ec505b35ea18760f1a23840a8a to your computer and use it in GitHub Desktop.
Save smitmartijn/2603a1ec505b35ea18760f1a23840a8a to your computer and use it in GitHub Desktop.
Laravel API token authentication
/**
* Laravel's Sanctum is not great at validating bearer tokens.
* If you want to validate a token for more than "does it exist", you need to do it manually.
* Here's an example inside an controller:
*/
class ApiSearchController extends Controller
{
public function store(Request $request)
{
if (!$request->bearerToken()) {
return response()->json([
'status' => 401,
'message' => 'Invalid API token!'
], 401);
}
$token = \Laravel\Sanctum\PersonalAccessToken::where('token', $request->bearerToken())->first();
if (!$token) {
return response()->json([
'status' => 401,
'message' => 'Invalid API token!'
], 401);
}
$user = $token->tokenable;
if (!$user) {
return response()->json([
'status' => 401,
'error' => 'Invalid API token!'
], 401);
}
if (!$user->onTrial() && !$user->subscribed()) {
return response()->json([
'status' => 401,
'error' => 'Your trial or subscription have expired'
], 401);
}
// do your thing
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment