Last active
August 6, 2016 11:00
-
-
Save hfalucas/697f03054c3ff7574d1aa0a048fe6cd1 to your computer and use it in GitHub Desktop.
[Laravel] JWT Login and Refresh token
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
<?php | |
$router->post('login', 'AuthenticationController@login'); | |
$router->post('logout', 'AuthenticationController@logout'); | |
$router->get('refresh-token', 'RefreshTokensController@refresh'); |
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
<?php | |
namespace Api\Http\Controllers\Auth; | |
use Tymon\JWTAuth\JWTAuth; | |
use Api\Http\Controllers\Controller; | |
use Api\Http\Requests\Auth\LoginRequest; | |
use Illuminate\Foundation\Auth\ThrottlesLogins; | |
class AuthenticationController extends Controller | |
{ | |
use ThrottlesLogins; | |
/** | |
* Logs in a user into the Api | |
* | |
* @param LoginRequest $request | |
* @return Response | |
*/ | |
public function login(LoginRequest $request) | |
{ | |
$credentials = $request->only('email', 'password'); | |
if (!$token = JWTAuth::attempt($credentials)) { | |
return resposne()->json(['message' => 'Your credentials are invalid'], 401); | |
} | |
return $this->respondWithUserAndToken($token); | |
} | |
/** | |
* Responds with the currently authenticated user. | |
* | |
* @param string $token | |
* @return Response | |
*/ | |
protected function respondWithUserAndToken($token) | |
{ | |
$user = JWTAuth::toUser($token); | |
return response()->json([ | |
'token' => $token, | |
'user' => [ | |
'id' => $user->id, | |
'name' => $user->name, | |
'email' => $user->email, | |
'role' => $user->role->name | |
] | |
]); | |
} | |
} |
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
<?php | |
namespace Api\Http\Controllers\Auth; | |
use Tymon\JWTAuth\JWTAuth; | |
class RefreshTokensController extends Controller | |
{ | |
/** | |
* Attempts to refresh a token | |
* | |
* @return Response | |
*/ | |
public function refresh() | |
{ | |
$token = JWTAuth::refresh(); | |
return response()->json(compact('token')); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment