1<?php
2
3namespace App\Http\Controllers;
4
5
6use Illuminate\Http\Request;
7use App\User;
8
9class AuthController extends Controller
10{
11 public $loginAfterSignUp = true;
12
13 public function register(Request $request)
14 {
15 $user = User::create([
16 'name' => $request->name,
17 'email' => $request->email,
18 'password' => bcrypt($request->password),
19 ]);
20
21 $token = auth()->login($user);
22
23 return $this->respondWithToken($token);
24 }
25
26 public function login(Request $request)
27 {
28 $credentials = $request->only(['email', 'password']);
29
30 if (!$token = auth()->attempt($credentials)) {
31 return response()->json(['error' => 'Unauthorized'], 401);
32 }
33
34 return $this->respondWithToken($token);
35 }
36 public function getAuthUser(Request $request)
37 {
38 return response()->json(auth()->user());
39 }
40 public function logout()
41 {
42 auth()->logout();
43 return response()->json(['message'=>'Successfully logged out']);
44 }
45 protected function respondWithToken($token)
46 {
47 return response()->json([
48 'access_token' => $token,
49 'token_type' => 'bearer',
50 'expires_in' => auth()->factory()->getTTL() * 60
51 ]);
52 }
53
54}
55
56
1# Database Preparation
2// add api_token to users table
3Schema::table('users', function ($table) {
4 $table->string('api_token', 80)->after('password')
5 ->unique()
6 ->nullable()
7 ->default(null);
8});
9
10// Create token for existing users, code can also be added to registerController
11 $token = Str::random(60);
12 $user = User::find(1);
13 $user->api_token = hash('sha256', $token); // <- This will be used in client access
14 $user->save();
15
16
17
18//config/auth.php
19 'guards' => [
20 'web' => [
21 'driver' => 'session',
22 'provider' => 'users',
23 ],
24
25 'api' => [
26 'driver' => 'token', // <- Add this entry
27 'provider' => 'users',
28 'hash' => false,
29 ],
30 ],
31
32
33
34//routes/api.php
35 // Add "middleware('auth:api')" as below
36 Route::middleware('auth:api')->get('/user', function (Request $request) {
37 return $request->user();
38 });
39
40
41
42//client access example (in Vue js)
43
44axios.get('http://example.com/api/user',
45 {
46 headers: {
47 'Accept': 'application/json',
48 'Authorization': 'Bearer '+ 'user-api-token'
49 }
50}
51 )
52 .then(function (response) {
53 // handle success
54 console.log(response);
55})
56 .catch(function (error) {
57 // handle error
58 console.log(error);
59})
60
61