iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
0

現在來帶入程式碼(下)的部分 GO GO GO !/images/emoticon/emoticon31.gif

JWT 身份要求

先在cmd打入下方代碼
在app/Http/Requests創建Request文件

php artisan make:request RegisterAuthRequest

app/Http/Requests/RegisterAuthRequest.php 裡面 新增程式碼

 <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class RegisterAuthRequest extends FormRequest
{

    public function authorize()
    {
        return true;
    }


    public function rules()
    {
        return [
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:6|max:10'
        ];
    }
}

在創建一个新的 ApiController

php artisan make:controller ApiController

在 app/Http/Controllers/ApiController.php 新增程式碼

<?php

namespace App\Http\Controllers;

use App\Http\Requests\RegisterAuthRequest;
use App\User;
use Illuminate\Http\Request;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class ApiController extends Controller
{
    public $loginAfterSignUp = true;

public function register(RegisterAuthRequest $request)
{
    $user = new User();
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = bcrypt($request->password);
    $user->save();

    if ($this->loginAfterSignUp) {
        return $this->login($request);
    }

    return response()->json([
        'success' => true,
        'data' => $user
    ], 200);
}

public function login(Request $request)
{
    $input = $request->only('email', 'password');
    $jwt_token = null;

    if (!$jwt_token = JWTAuth::attempt($input)) {
        return response()->json([
            'success' => false,
            'message' => 'Invalid Email or Password',
        ], 401);
    }

    return response()->json([
        'success' => true,
        'token' => $jwt_token,
    ]);
}

public function logout(Request $request)
{
    $this->validate($request, [
        'token' => 'required'
    ]);

    try {
        JWTAuth::invalidate($request->token);

        return response()->json([
            'success' => true,
            'message' => 'User logged out successfully'
        ]);
    } catch (JWTException $exception) {
        return response()->json([
            'success' => false,
            'message' => 'Sorry, the user cannot be logged out'
        ], 500);
    }
}

public function getAuthUser(Request $request)
{
    $this->validate($request, [
        'token' => 'required'
    ]);

    $user = JWTAuth::authenticate($request->token);

    return response()->json(['user' => $user]);
}
}

這樣就完成JWT的身份驗證了

參考


上一篇
[Day08] 後端07:JWT CODE(上)
下一篇
[Day10] 後端09:說明保留字
系列文
普通人寫前後端,可以挺過30天 吧!?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言