A helpful Postman Pre-request Script which will log you into Laravel Sanctum, using environment variables and attach the token as an Authorization header before calling the request.
Created
October 4, 2023 23:24
-
-
Save elliotlings/b335e0b07b0109987adea59da1c929d2 to your computer and use it in GitHub Desktop.
Laravel Sanctum Postman Pre-request Login Script
This file contains hidden or 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
let token = pm.environment.get('token'); | |
if (! token) { | |
let email = pm.environment.get('email'); | |
let password = pm.environment.get('password'); | |
let loginRequest = { | |
url: loginUrl = pm.environment.get('url') + '/api/login', | |
method: 'POST', | |
headers: { | |
Accept: 'application/json', | |
'Content-Type': 'multipart/form-data', | |
}, | |
body: { | |
'mode': 'formdata', | |
'formdata': [ | |
{'key':'email', 'value': email}, | |
{'key':'password', 'value': password}, | |
{'key': 'device_name', 'value': 'postman'} | |
] | |
} | |
}; | |
pm.sendRequest(loginRequest, function(err, res) { | |
const token = res.json().data.token; | |
pm.environment.set('token', token); | |
pm.request.headers.upsert({ | |
key: 'Authorization', | |
value: 'Bearer ' + token, | |
}); | |
}); | |
} else { | |
pm.request.headers.upsert({ | |
key: 'Authorization', | |
value: 'Bearer ' + token, | |
}); | |
} |
This file contains hidden or 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
<?php | |
use App\Models\User; | |
use Illuminate\Http\Request; | |
use Illuminate\Support\Facades\Route; | |
use Illuminate\Validation\ValidationException; | |
Route::post('/login', function (Request $request) { | |
$request->validate([ | |
'email' => 'required|email', | |
'password' => 'required', | |
'device_name' => 'required', | |
]); | |
$user = User::where('email', $request->email)->first(); | |
if (! $user || ! Hash::check($request->password, $user->password)) { | |
throw ValidationException::withMessages([ | |
'email' => ['The provided credentials are incorrect.'], | |
]); | |
} | |
return [ | |
'data' => [ | |
'token' => $user->createToken($request->device_name)->plainTextToken, | |
'user' => $user->only('id', 'name', 'email'), | |
], | |
]; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment