Home PHP Framework Laravel laravel installation jwt-auth and verification (example)

laravel installation jwt-auth and verification (example)

May 28, 2020 am 10:37 AM
laravel

laravel installation jwt-auth and verification (example)


laravel Install jwt-auth and verify


##1. Use composer to install jwt, cmd to the project folder;

composer require tymon/jwt-auth 1.0.* (Write the version number here according to your own needs)

Install jwt, refer to the official documentation

https: //jwt-auth.readthedocs.io/en/docs/laravel-installation/

2. If the laravel version is lower than 5.4

Open config/app in the root directory. php

Add Tymon\JWTAuth\Providers\LaravelServiceProvider::class,

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

3. Add a jwt.php configuration file under config

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

4. Generate an encryption key under the .env file, such as: JWT_SECRET=foobar

php artisan jwt:secret

5. Write the following code in the user model

<?php
namespace App\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
        // Rest omitted for brevity
    protected $table="user";
    public $timestamps = false;
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }
    public function getJWTCustomClaims()
    {
        return [];
    }
}
Copy after login

6. Register two Facade

config/app.php

&#39;aliases&#39; => [
        ...
        // 添加以下两行
        &#39;JWTAuth&#39; => &#39;Tymon\JWTAuth\Facades\JWTAuth&#39;,
        &#39;JWTFactory&#39; => &#39;Tymon\JWTAuth\Facades\JWTFactory&#39;,
],
Copy after login

7. Modify auth.php

config/auth.php

&#39;guards&#39; => [
    &#39;web&#39; => [
        &#39;driver&#39; => &#39;session&#39;,
        &#39;provider&#39; => &#39;users&#39;,
    ],
    &#39;api&#39; => [
        &#39;driver&#39; => &#39;jwt&#39;,      // 原来是 token 改成jwt
        &#39;provider&#39; => &#39;users&#39;,
    ],
],
Copy after login

8. Register route

Route::group([
    &#39;prefix&#39; => &#39;auth&#39;
], function ($router) {
    $router->post(&#39;login&#39;, &#39;AuthController@login&#39;);
    $router->post(&#39;logout&#39;, &#39;AuthController@logout&#39;);
});
Copy after login

9. Create token controller

php artisan make:controller AuthController

The code is as follows:

<?php
namespace App\Http\Controllers;
use App\Model\User;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(&#39;auth:api&#39;, [&#39;except&#39; => [&#39;login&#39;]]);
    }
    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request([&#39;email&#39;, &#39;password&#39;]);
        if (! $token = auth(&#39;api&#39;)->attempt($credentials)) {
            return response()->json([&#39;error&#39; => &#39;Unauthorized&#39;], 401);
        }
        return $this->respondWithToken($token);
    }
    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(JWTAuth::parseToken()->touser());
    }
    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        JWTAuth::parseToken()->invalidate();
        return response()->json([&#39;message&#39; => &#39;Successfully logged out&#39;]);
    }
    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(JWTAuth::parseToken()->refresh());
    }
    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            &#39;access_token&#39; => $token,
            &#39;token_type&#39; => &#39;bearer&#39;,
            &#39;expires_in&#39; => JWTAuth::factory()->getTTL() * 60
        ]);
    }
}
Copy after login

Note: attempt It keeps returning false because the password is encrypted. Just use bcrypt or password_hash to encrypt it.

10. Verify token to obtain user information.

There are two ways to use it:

Add to the url:?token=your token

Add to the header, it is recommended to use this, because it is more secure under https: Authorization:Bearer your token

11, First, use the artisan command to generate a middleware. I named it RefreshToken.php here. After the creation is successful, you need to inherit the JWT BaseMiddleware

The code is as follows:

<?php
namespace App\Http\Middleware;
use Auth;
use Closure;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
// 注意,我们要继承的是 jwt 的 BaseMiddleware
class RefreshToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @ param  \Illuminate\Http\Request $request
     * @ param  \Closure $next
     *
     * @ throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
     *
     * @ return mixed
     */
    public function handle($request, Closure $next)
    {
        // 检查此次请求中是否带有 token,如果没有则抛出异常。
        $this->checkForToken($request);
        // 使用 try 包裹,以捕捉 token 过期所抛出的 TokenExpiredException  异常
        try {
            // 检测用户的登录状态,如果正常则通过
            if ($this->auth->parseToken()->authenticate()) {
                return $next($request);
            }
            throw new UnauthorizedHttpException(&#39;jwt-auth&#39;, &#39;未登录&#39;);
        } catch (TokenExpiredException $exception) {
            // 此处捕获到了 token 过期所抛出的 TokenExpiredException 异常,我们在这里需要做的是刷新该用户的 token 并将它添加到响应头中
            try {
                // 刷新用户的 token
                $token = $this->auth->refresh();
                // 使用一次性登录以保证此次请求的成功
                Auth::guard(&#39;api&#39;)->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()[&#39;sub&#39;]);
            } catch (JWTException $exception) {
                // 如果捕获到此异常,即代表 refresh 也过期了,用户无法刷新令牌,需要重新登录。
                throw new UnauthorizedHttpException(&#39;jwt-auth&#39;, $exception->getMessage());
            }
        }
        // 在响应头中返回新的 token
        return $this->setAuthenticationHeader($next($request), $token);
    }
}
Copy after login

The main thing that needs to be said here is After the token is refreshed, not only does the token need to be placed in the return header, it is also best to replace the token in the request header, because after the refresh, the token in the request header has become invalid. If the business logic in the interface uses the request token in the header, then problems will arise.

Here we use

$request->headers->set(&#39;Authorization&#39;,&#39;Bearer &#39;.$token);
Copy after login

to refresh the token in the request header.

After creating and writing the middleware, just register the middleware and add some exception handling in App\Exceptions\Handler.php.

12. Add middleware configuration in

$routeMiddleware in kernel.php file

&#39;RefreshToken&#39; => \App\Http\Middleware\RefreshToken::class,
Copy after login

13. Add routing

Route::group([&#39;prefix&#39; => &#39;user&#39;],function($router) {
    $router->get(&#39;userInfo&#39;,&#39;UserController@userInfo&#39;)->middleware(&#39;RefreshToken&#39;);
});
Copy after login

Pass JWTAuth in the controller: :user(); can obtain user information

For more laravel framework technical articles, please visit

laraveltutorial!

The above is the detailed content of laravel installation jwt-auth and verification (example). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Which is the better template engine, Laravel or CodeIgniter? Which is the better template engine, Laravel or CodeIgniter? Jun 03, 2024 am 11:30 AM

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

Laravel - Artisan Console Laravel - Artisan Console Aug 27, 2024 am 10:51 AM

Laravel - Artisan Console - Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail.

See all articles