Laradebut #7 - Laravel Auth

Cara Wang <caraw@cnyes.com>

Laradebut #7

會員系統 Authentication

@author Cara Wang <caraw@cnyes.com>

@since 2017/03/28

PHP Developer

  1. 2014/09 ~ now

會員系統要素

兩種架構

Server Based Authentication
Server Based Authentication
Server Based Authentication
Server Based Authentication - 其他 Request 需要驗證登入狀況時
Server Based Authentication - 其他 Request 需要驗證登入狀況時
Server Based Authentication - 其他 Request 需要驗證登入狀況時

兩種架構

  1. Server Based Authentication
Token Based Authentication
Token Based Authentication
Token Based Authentication - 其他 Request 需要驗證登入狀況時
Token Based Authentication - 其他 Request 需要驗證登入狀況時

兩種架構

  1. Server Based Authentication
    1. 單靠後端操作使用者的登入狀況
    2. 使用 Session 與 Cookies 記錄使用者登入狀況
    3. 適合用在目標客戶只有瀏覽器的產品
  1. Token Based Authentication

兩種架構 - 實作會員系統要素的差異

兩種架構 - 實作會員系統要素的差異

聽起來很複雜...

Laravel 提供完整的 Server Based Authentication

php artisan make:auth
php artisan serve
php artisan make:auth 後的 code change

聽起來很複雜...

Laravel 提供完整的 Server Based Authentication

php artisan make:auth
php artisan serve
php artisan migrate

如果你使用 Laravel 5.4 + MySQL 5.6 或以下版本

如果你使用 Laravel 5.4 + MySQL 5.6 或以下版本

			namespace App\Providers;
			use Illuminate\Support\Facades\Schema;
			class AppServiceProvider extends ServiceProvider
                        {
			    public function boot()
			    {
			         Schema::defaultStringLength(191);
			    }
			}
		

Ref: https://laravel-news.com/laravel-5-4-key-too-long-error

Server Based Authentication
Server Based Authentication - Laravel
Server Based Authentication
Server Based Authentication - Laravel
Server Based Authentication
Server Based Authentication - Laravel
Server Based Authentication
Server Based Authentication - Laravel

記得我

1|EWnGacWd8GnEUVdeeki0GLs70tjJCfb9jph2LkAbvkdTq0e8SHhA2L8mUWb0
Server Based Authentication - Remember Me
Server Based Authentication - Remember Me

Laravel 提供的 Token Based Authentication?

https://gistlog.co/JacobBennett/090369fbab0b31130b51

Laravel 提供的 Token Based Authentication?

			namespace App\Http\Controllers\Auth;
			use Illuminate\Http\Request;
			...
			public function apiRegister(Request $request)
    		{
        		$data = $request->json()->all();
        		$this->validator($data)->validate();
			 
				$data['token'] = str_random(20);
				$user = $this->create($data);
			 
				return response()->json(['token' => $data['token']]);
    		}
		

使用以下 Package:

  • tymondesigns/jwt-auth
  • 			// 1. install package
    			composer require tymon/jwt-auth
    			// 2. modify config/app.php
    			'providers' => [
    				Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,
    			],
    			'aliases' => [
    				'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    			],
    			// 3. setup config
    			php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
    			php artisan jwt:generate
    		

    撰寫 登入 機制

    			namespace App\Http\Controllers\Auth;
    			use JWTAuth;
    			use Illuminate\Http\Request;
    			 
    			class LoginController extends Controller
    			{
    				public function apiLogin(Request $request)
        			{
            			$data = $request->json()->all();
            			$token = JWTAuth::attempt($data);
            			if (!$token) {
                			return response()->json(['error' => 'Invalid User']);
            			}
            			return response()->json(['token' => $token]);
        			}
        		}
    		

    撰寫 登入 機制

    			// route/api.php
    			Route::post('/login', 'Auth\LoginController@apiLogin');
    		

    讓 Error 的 API Response 也是 Json 格式

    			namespace App\Exceptions;
    			class Handler extends ExceptionHandler
    			{
    				public function render($request, Exception $exception)
    				{
    				    if ($request->expectsJson()) {
    			          return response()->json(['error' => $exception->getMessage()], 500);
    				    }
    			  
    			      return parent::render($request, $exception);
    				}
    			}
    		
    Token Based Authentication
    Token Based Authentication - Laravel

    測試其他 Request

    			// route/api.php
    			use Tymon\JWTAuth\Facades\JWTAuth;
    			Route::middleware('jwt')->get('/user', function (Request $request) {
    				return JWTAuth::parseToken()->toUser();
    			});
    		

    撰寫 Middleware

    php artisan make:middleware JWTAuthentication
                        namespace App\Http\Middleware;
                        use JWTAuth;
                           
                        class JWTAuthentication
                        {
                            public function handle($request, Closure $next)
                            {
                              JWTAuth::parseToken()->authenticate();
                         
                              return $next($request);
                            }
                        }
    		

    撰寫 Middleware

    			namespace App\Http;
    			class Kernel extends HttpKernel
    			{
    				protected $routeMiddleware = [
    					'jwt' => \App\Http\Middleware\JWTAuthentication::class
    				];
    			}
    		
    Token Based Authentication
    Token Based Authentication - Laravel

    記得我

    			// route/api.php
    			Route::get('/refresh', 'Auth\LoginController@refreshToken');
    		
    			public function refreshToken()
        		{
    				$newToken = JWTAuth::parseToken()->refresh();
            		return response()->json(['token' => $newToken]);
        		}
    		
    Token Based Authentication - Remember Me

    聽起來好像很簡單!?

    如果都不想自己撰寫驗證程式

    Q & A

    Fork me on GitHub