Skip to content

Instantly share code, notes, and snippets.

@hfalucas
Last active August 6, 2016 11:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hfalucas/697f03054c3ff7574d1aa0a048fe6cd1 to your computer and use it in GitHub Desktop.
[Laravel] JWT Login and Refresh token
<?php
$router->post('login', 'AuthenticationController@login');
$router->post('logout', 'AuthenticationController@logout');
$router->get('refresh-token', 'RefreshTokensController@refresh');
<?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
]
]);
}
}
<?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