jwt-auth laravel 8 code example
Example 1: laravel jwt user create
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Validator;
use App\User;
class AuthController extends Controller {
public function __construct() {
$this->middleware('auth:api', ['except' => ['login', 'register']]);
}
public function login(Request $request){
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required|string|min:6',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 422);
}
if (! $token = auth()->attempt($validator->validated())) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->createNewToken($token);
}
public function register(Request $request) {
$validator = Validator::make($request->all(), [
'name' => 'required|string|between:2,100',
'email' => 'required|string|email|max:100|unique:users',
'password' => 'required|string|confirmed|min:6',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create(array_merge(
$validator->validated(),
['password' => bcrypt($request->password)]
));
return response()->json([
'message' => 'User successfully registered',
'user' => $user
], 201);
}
public function logout() {
auth()->logout();
return response()->json(['message' => 'User successfully signed out']);
}
public function refresh() {
return $this->createNewToken(auth()->refresh());
}
public function userProfile() {
return response()->json(auth()->user());
}
protected function createNewToken($token){
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60,
'user' => auth()->user()
]);
}
}
Example 2: jwt laravel
php artisan jwt:secret
Example 3: laravel jwt
composer require tymon/jwt-auth
Example 4: laravel JWTAuthentication
$ composer require tymon/jwt-auth:dev-develop
Example 5: jwt laravel
php artisan vendor:publish
Example 6: jwt auth laravel auth without password field
public function authenticate(Request $request) {
$email = $request->input('email');
$user = User::where('email', '=', $email)->first();
try {
if (! $token = JWTAuth::fromUser($user)) {
return response()->json(['error' => 'invalid_credentials'], 401);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('token'));
}