Created
November 11, 2018 02:15
-
-
Save bran921007/6206f56975480c5a29c6dc3ecaa10b7e to your computer and use it in GitHub Desktop.
JWT authentication for Lumen 5.6
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 | |
namespace App\Http\Controllers; | |
use Validator; | |
use App\User; | |
use Firebase\JWT\JWT; | |
use Illuminate\Http\Request; | |
use Firebase\JWT\ExpiredException; | |
use Illuminate\Support\Facades\Hash; | |
use Laravel\Lumen\Routing\Controller as BaseController; | |
class AuthController extends BaseController | |
{ | |
/** | |
* The request instance. | |
* | |
* @var \Illuminate\Http\Request | |
*/ | |
private $request; | |
/** | |
* Create a new controller instance. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return void | |
*/ | |
public function __construct(Request $request) { | |
$this->request = $request; | |
} | |
/** | |
* Create a new token. | |
* | |
* @param \App\User $user | |
* @return string | |
*/ | |
protected function jwt(User $user) { | |
$payload = [ | |
'iss' => "lumen-jwt", // Issuer of the token | |
'sub' => $user->id, // Subject of the token | |
'iat' => time(), // Time when JWT was issued. | |
'exp' => time() + 60*60 // Expiration time | |
]; | |
// As you can see we are passing `JWT_SECRET` as the second parameter that will | |
// be used to decode the token in the future. | |
return JWT::encode($payload, env('JWT_SECRET')); | |
} | |
/** | |
* Authenticate a user and return the token if the provided credentials are correct. | |
* | |
* @param \App\User $user | |
* @return mixed | |
*/ | |
public function authenticate(User $user) { | |
$this->validate($this->request, [ | |
'email' => 'required|email', | |
'password' => 'required' | |
]); | |
// Find the user by email | |
$user = User::where('email', $this->request->input('email'))->first(); | |
if (!$user) { | |
// You wil probably have some sort of helpers or whatever | |
// to make sure that you have the same response format for | |
// differents kind of responses. But let's return the | |
// below respose for now. | |
return response()->json([ | |
'error' => 'Email does not exist.' | |
], 400); | |
} | |
// Verify the password and generate the token | |
if (Hash::check($this->request->input('password'), $user->password)) { | |
return response()->json([ | |
'token' => $this->jwt($user) | |
], 200); | |
} | |
// Bad Request response | |
return response()->json([ | |
'error' => 'Email or password is wrong.' | |
], 400); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment