jwt-auth
jwt-auth copied to clipboard
JWTAuth::getJWTProvider()->setSecret( ... dosent work
JWTAuth::getJWTProvider()->setSecret(... dosent work.
Steps to reproduce
- Crate a larval project add "tymon/jwt-auth": "^2.1"
- generate the secret php artisan jwt:secret
- save as secret app1 ex 'ZNF9rMdaAq8AI3koJ1AfNfokm9o5kZ3dnts4qirwIl0QErgDkf05umHUVa88rqeo'
- test an api login
- php artisan jwt:secret
- test api login
- create a controller for login app1
- add _construct()
api for keys
public function __construct()
{
// Get the secret key for the application context from configuration
$this->secretKey = 'ZNF9rMdaAq8AI3koJ1AfNfokm9o5kZ3dnts4qirwIl0QErgDkf05umHUVa88rqeo'
// Set the secret key for JWT authentication
JWTAuth::getJWTProvider()->setSecret($this->secretKey);
}
public function loginUser(Request $request)
{
$credentials = $request->only('email', 'password');
try {
$token = auth()->guard('appOne')->attempt($credentials, ['secret' => $this->secretKey]);
if (!$token) {
return response()->json(['success' => false, 'error' => 'Some Error Message'], 401);
}
} catch (JWTException $e) {
return response()->json(['success' => false, 'error' => 'Failed to login, please try again.'], 500);
}
$user = Auth::guard('appOne')->user();
$customClaims = $user->getJWTCustomClaims();
$response =[
'token' => $token,
'customClaims' => $customClaims,
'claims' => JWTAuth::claims($customClaims)->fromUser($user),
'secretKey' => $this->secretKey,
'getVerificationKey' =>JWTAuth::getJWTProvider()->getVerificationKey()
];
return $this->finalResponse($response);
}
ApiOne
public function verifyToken(Request $request)
{
try {
$token = $request->bearerToken() ?: $request->query('token');
JWTAuth::setToken($token);
$user = Auth::guard('api')->user();
$customClaims = $user->getJWTCustomClaims();
$response =[
'user' => $user,
'customClaims' => $customClaims,
'claims' => JWTAuth::claims($customClaims)->fromUser($user),
];
return response()->json(['response' => $response], 200);
} catch (\Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
// Token has expired
return response()->json(['error' => 'Token expired'], 401);
} catch (\Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
// Token is invalid
return response()->json(['error' => 'Token invalid'], 401);
} catch (\Tymon\JWTAuth\Exceptions\JWTException $e) {
// Token is absent from the request
return response()->json(['error' => 'Token absent'], 401);
}
}
- in the new project try app1 for verify user
- not working
- try secret from the first app works
Expected behaviour
I was Expected to use the app1 ex 'ZNF9rMdaAq8AI3koJ1AfNfokm9o5kZ3dnts4qirwIl0QErgDkf05umHUVa88rqeo' as JWT_SECRET i
Actual behaviour
not working with 'ZNF9rMdaAq8AI3koJ1AfNfokm9o5kZ3dnts4qirwIl0QErgDkf05umHUVa88rqeo' as JWT_SECRET working with main app secret