Skip to content

Commit a97d307

Browse files
committed
JWT Authentication and APIs
1 parent fe6eeb9 commit a97d307

File tree

7 files changed

+716
-6
lines changed

7 files changed

+716
-6
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
3+
namespace App\Http\Controllers;
4+
5+
use Illuminate\Http\Request;
6+
7+
class AuthController extends Controller
8+
{
9+
public function __construct()
10+
{
11+
$this->middleware('auth:api', ['except' => ['login']]);
12+
}
13+
14+
public function login() {
15+
$credentials = request(['email', 'password']);
16+
17+
if (! $token = auth()->attempt($credentials)) {
18+
return response()->json(['error' => 'Invalid email or password'], 401);
19+
}
20+
21+
return $this->respondWithToken($token);
22+
}
23+
24+
private function respondWithToken($token) {
25+
return response()->json([
26+
'token' => $token,
27+
'access_type' => 'bearer',
28+
'expires_in' => auth()->factory()->getTTL() * 60
29+
]);
30+
}
31+
32+
33+
public function logout() {
34+
auth()->logout();
35+
return response()->json(['msg' => 'User successfully logged out']);
36+
}
37+
38+
39+
public function refresh() {
40+
return $this->respondWithToken(auth()->refresh());
41+
}
42+
43+
public function me() {
44+
return response()->json(auth()->user());
45+
}
46+
}

app/User.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
use Illuminate\Contracts\Auth\MustVerifyEmail;
66
use Illuminate\Foundation\Auth\User as Authenticatable;
77
use Illuminate\Notifications\Notifiable;
8+
use Tymon\JWTAuth\Contracts\JWTSubject;
89

9-
class User extends Authenticatable
10+
class User extends Authenticatable implements JWTSubject
1011
{
1112
use Notifiable;
1213

@@ -36,4 +37,20 @@ class User extends Authenticatable
3637
protected $casts = [
3738
'email_verified_at' => 'datetime',
3839
];
40+
41+
/**
42+
* @inheritDoc
43+
*/
44+
public function getJWTIdentifier()
45+
{
46+
return $this->getKey();
47+
}
48+
49+
/**
50+
* @inheritDoc
51+
*/
52+
public function getJWTCustomClaims()
53+
{
54+
return [];
55+
}
3956
}

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"fruitcake/laravel-cors": "^1.0",
1414
"guzzlehttp/guzzle": "^6.3",
1515
"laravel/framework": "^7.0",
16-
"laravel/tinker": "^2.0"
16+
"laravel/tinker": "^2.0",
17+
"tymon/jwt-auth": "^1.0"
1718
},
1819
"require-dev": {
1920
"facade/ignition": "^2.0",

0 commit comments

Comments
 (0)