I have API Laravel project and I am using JWT authentication and in the respondWithToken()
I changed getTTL() * 60
to getTTL() * 1440
and it still return 401 Unauthorized
error after about 1 hour
And this is the controller functions
public function login(Request $request)
{
$credentials = $request->only(['email', 'password']);
if (!$token = auth()->guard('admin_api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
$response = [];
array_push($response, $this->respondWithToken($token), $this->me());
return response()->json($response);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth('admin_api')->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth('admin_api')->logout();
return response()->json(['message' => 'Successfully Logged Out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth('admin_api')->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
public function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->guard('admin_api')->factory()->getTTL() * 1440
]);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|min:8'
]);
if ($validator->fails()) {
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(
array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
)
);
return response()->json([
'message' => 'Admin Registered Successfully',
'admin' => $user
], 201);
}
Can anyone help me recognize how to fix this issue?
CodePudding user response:
I'm using jwt configuration file:
- Publish config file(if not already)
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
- Set
JWT_TTL
in minutes in your .env file
JWT_TTL=1440 #set expiration to 1 day
- read expiration time from config file
protected function respondWithToken(string $token): JsonResponse
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => config('jwt.ttl') * 60,
]);
}