Created
April 11, 2023 15:13
-
-
Save smitmartijn/2603a1ec505b35ea18760f1a23840a8a to your computer and use it in GitHub Desktop.
Laravel API token authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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