57
loading...
This website collects cookies to deliver better user experience
composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
php artisan jwt:secret
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
// Rest omitted for brevity
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
......
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
Route::post('register', [JwtAuthController::class, 'register'])->name('api.jwt.register');
Route::post('login', [JwtAuthController::class, 'login'])->name('api.jwt.login');
Route::group(['middleware' => 'auth:api'], function(){
Route::get('user', [JwtAuthController::class, 'me'])->name('api.jwt.user');
Route::get('refresh', [JwtAuthController::class, 'refresh'])->name('api.jwt.refresh');
Route::get('logout', [JwtAuthController::class, 'logout'])->name('api.jwt.logout');
});
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class JwtAuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function register(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:100',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|string|min:8|max:255|confirmed',
'password_confirmation' => 'required|string|min:8|max:255',
]);
$user = new User;
$user->fill($request->all());
$user->password = bcrypt($request->password);
$user->save();
return response()->json([
'status' => 'success',
'data' => $user
], 200);
}
/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = Auth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(Auth::user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
Auth::logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(Auth::refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => Auth::factory()->getTTL() * 60
]);
}
}
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ",
"token_type": "bearer",
"expires_in": 3600
}