Laravel 5.5 JWT Authentication

Sample code used in the video tutorial

TokenController.php

<?php

namespace App\Http\Controllers\API\Auth;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Validator;
use JWTAuth;

class TokenController extends Controller {

    public function auth(Request $request) {
        $credentials = $request->only('email', 'password');

        $validator = Validator::make($credentials, [
                    'email' => 'required|email',
                    'password' => 'required'
        ]);

        if ($validator->fails()) {
            return response()
                            ->json([
                                'code' => 1,
                                'message' => 'Validation failed.',
                                'errors' => $validator->errors()
                                    ], 422);
        }

        $token = JWTAuth::attempt($credentials);

        if ($token) {
            return response()->json(['token' => $token]);
        } else {
            return response()->json(['code' => 2, 'message' => 'Invalid credentials.'], 401);
        }
    }

    public function refresh() {
        $token = JWTAuth::getToken();
        try {
            $token = JWTAuth::refresh($token);
            return response()->json(['token' => $token]);
        } catch (TokenExpiredException $e) {
            //token cannot be refreshed, user needs to login again
            throw new HttpResponseException(
            Response::json(['msg' => "Need to Login Again"])
            );
        }
    }
    
    public function invalidate() {
        $token = JWTAuth::getToken();
        try {
            $token = JWTAuth::invalidate($token);
            return response()->json(['token' => $token]);
        } catch (Exception $e) {
            
        }
    }

}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *