Làm mới mã thông báo jwt php

Hôm nay mình chia sẻ với mọi người cách tích hợp xác thực Authentication Json Web Token (JWT) to Laravel 8. Đầu tiên bạn vào đường dẫn sau để download hoặc git clone source về máy tính nhé. https. //github. com/laravel/laravel/tree/8. x

Sau khi tải về, bạn tiến hành giải nén và cd tới thư mục dự án đã chạy lệnh. cài đặt nhà soạn nhạc để cài đặt các thư viện cần thiết của laravel, bạn sẽ thấy nhà cung cấp thư mục

Được rồi giờ hãy tạo cơ sở dữ liệu cơ sở dữ liệu, nếu bạn đã có sẵn thì tiến hành mở tệp. env up edit connect to your database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=jwt
DB_USERNAME=root
DB_PASSWORD=MẬT_KHẨU_MYSQL

Tiến hành chạy câu lệnh. nghệ nhân php di chuyển

Laravel sẽ tạo các bảng cần thiết cho cơ sở dữ liệu của bạn, bạn có thể vào cơ sở dữ liệu để xem thử nhé

# Cài đặt cấu hình JWT trong laravel bằng câu lệnh sau

composer require tymon/jwt-auth:^1.0.2

Làm mới mã thông báo jwt php

Sau khi cài đặt thành công. tiếp theo ta cần phải tích hợp một số mã vào tệp config/app. php

'providers' => [
    ....
    ....
    Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],

Thêm các mặt tiền sau vào aliases mảng

'aliases' => [
    ....
    'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
    'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
    ....
],

Tiếp theo, sử dụng lệnh sau để công khai tệp JWT Auth từ nhà cung cấp sang config/jwt. php

php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"

Làm mới mã thông báo jwt php

Tiếp theo là việc tạo mã khóa bí mật của ta thôi, nó là mã hóa khóa bí mật

php artisan jwt:secret

Làm mới mã thông báo jwt php

Bạn sẽ thấy khóa bí mật được tạo trong tệp. env

* Thiết lập Model User

Các bạn mở tệp App\Models\User. php up và triển khai giao diện Tymon\JWTAuth\Contracts\JWTSubject;

 'datetime',
    ];

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier() {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims() {
        return [];
    }
}

Các bạn lưu ý ở mình Class User mình có implements JWTSubject, đồng thời mình thêm 2 hàm này(getJWTCustomClaims,getJWTIdentifier)

# Thiết lập JWT Auth Guard để bảo vệ quá trình xác thực của ứng dụng Laravel

Please open file config/auth. php up and edit edit as after

 /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
 
    */

    'defaults' => [
        'guard' => 'api',//default "web"
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards

    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'jwt',  //default "token"
            'provider' => 'users',
            'hash' => false,
        ],
    ],

 

# Create Controller for user user

Bạn chạy câu lệnh bên dưới sẽ được một tệp AuthController. php trong thư mục App\Controllers\Api

________số 8

Bạn mở tệp lên và viết các phương thức Đăng nhập, Đăng ký, Tải lại mã thông báo, Thay đổi mật khẩu,

middleware('auth:api', ['except' => ['login', 'register']]);
     
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
    	$validator = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        if (! $token = auth('api')->attempt($validator->validated())) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->createNewToken($token);
    }

    /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request) {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|between:2,100',
            'email' => 'required|string|email|max:100|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }

        $user = User::create(array_merge(
                    $validator->validated(),
                    ['password' => bcrypt($request->password)]
                ));

        return response()->json([
            'message' => 'User successfully registered',
            'user' => $user
        ], 201);
    }


    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout() {
        auth('api')->logout();

        return response()->json(['message' => 'User successfully signed out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh() {
        return $this->createNewToken(auth('api')->refresh());
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function userProfile() {
        return response()->json(auth('api')->user());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function createNewToken($token){
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60,
            'user' =>auth('api')->user()
        ]);
    }

    public function changePassWord(Request $request) {
        $validator = Validator::make($request->all(), [
            'old_password' => 'required|string|min:6',
            'new_password' => 'required|string|confirmed|min:6',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }
        $userId =auth('api')->user()->id;

        $user = User::where('id', $userId)->update(
                    ['password' => bcrypt($request->new_password)]
                );

        return response()->json([
            'message' => 'User successfully changed password',
            'user' => $user,
        ], 201);
    }
}

Okay mình sẽ giải thích sơ qua cho mọi người hiểu cơ chế xử lý nó như thế nào nhé

1. Đăng ký người dùng ta cần khi báo 4 tham số (tên,email,mật khẩu, password_confirmation)

2. Đăng nhập ta cần 2 tham số(email,password), nếu đăng nhập thành công ta sẽ nhận được access_token

3. Get access_token được gắn vào header Bearer token để có thể lấy thông tin người dùng

4. Nếu access_token hết hạn, ta cần gửi access_token đến server để tạo lại token mới cho ta (nhớ là phải gắn nó vào header bearer token nhé)

5. Thoát ta cũng như bước 2,3 cũng kèm theo access_token đó trong header bearer token

6. Đổi mật khẩu ta cần gửi 3 tham số (email, old_password, new_password, new_password_confirmation) , đồng thời cũng kèm theo access_token đến trong header nhé

# Thiết lập Tuyến đường

Hãy mời các tuyến đường/api. php

composer require tymon/jwt-auth:^1.0.2
0

Giờ chúng ta thực hành thôi, giờ làm từ a lưa hết rồi, không biết có chạy không kaka, chạy server thôi. nghệ nhân php phục vụ

Hình 1. Đăng ký

Làm mới mã thông báo jwt php

 

Hình 2. Đăng nhập

Làm mới mã thông báo jwt php

Hình 3. lấy thông tin người dùng, chúng ta cần lấy access_token trả về khi đăng nhập, gắn vào mã thông báo mang tiêu đề để lấy thông tin người dùng

Làm mới mã thông báo jwt php

 

Hình 4. Mã thông báo đăng xuất, chúng tôi cần lấy mã thông báo truy cập trước đó được gắn trong mã thông báo mang tiêu đề. To handle logout

Làm mới mã thông báo jwt php

 

Hình 5. Giả sử bạn chưa đăng xuất, bạn còn dẫn access_token mà nó đã hết hạn, thì bạn có thể gắn refresh token để tạoToken mới về cho ta, cách làm cũng như các bước trên, gắn token vào header bearer token

Làm mới mã thông báo jwt php

Hình 6. Lấy access_token gắn vào header bearer token để cập nhật mật khẩu nhé

Làm mới mã thông báo jwt php

Được rồi vậy là xong , các bạn có thể thực hiện hành động thử nhé. ở đây mình chia sẻ một số kinh nghiệm khi gặp phải như sau

- Giả sử web bạn đã cài đặt php artisan make. auth rồi, giờ bạn muốn gắn jwt nửa, bạn sẽ gặp một lỗi là sử dụng auth đăng nhập trên web không được, mà đăng nhập jwt api trên postman thì ok.  

- Chính vì trong Auth nó cũng sử dụng auth()->user() nó đụng với jwt mà bạn thấy người ta thường cài đặt auth()->user() nửa

- Chính vì thế mà bạn có thể xem lại đoạn mã bên trên của mình chỉ được xác định gàn cho auth('api')->user() trong tệp AuthController. To hide image Xung đột lẫn nhau

Thì lúc này bạn đã có thể vừa sử dụng đăng nhập auth trên web vừa sử dụng jwt api bên người đưa thư

Nói chung hơi lu bu, Mình cũng mới gặp phải, nên chia sẻ với mọi người, nếu mọi người gặp phải thì xử lý vụ đó thử xem nhé