Home > Backend Development > PHP Tutorial > Implementing PHP security verification using Laravel Passport

Implementing PHP security verification using Laravel Passport

王林
Release: 2023-07-25 21:34:01
Original
1525 people have browsed it

Using Laravel Passport to implement PHP security authentication

Introduction:
In modern web development, user authentication and authorization are very important security functions. Laravel Passport is an OAuth2-based authentication tool that can help us easily implement user authentication and authorization functions. This article explains how to implement secure authentication in PHP using Laravel Passport.

Steps:

  1. Install Laravel Passport
    First, make sure the Laravel framework is installed. Next, enter the project directory in the terminal and execute the following command to install the Laravel Passport package:

    composer require laravel/passport
    Copy after login

    After successful installation, run the following command to publish the files and database migrations required by the package:

    php artisan passport:install
    Copy after login
  2. Configure Passport
    Open the config/app.php file and add the following service provider in the providers array:

    LaravelPassportPassportServiceProvider::class,
    Copy after login

    Then, in the $routeMiddleware array in the app/Http/Kernel.php file, add the following middleware:

    'client' => LaravelPassportHttpMiddlewareCheckClientCredentials::class,
    Copy after login

    Finally, in the app /User.php Add the HasApiTokens trait of Passport to the /User.php

    file:

    use LaravelPassportHasApiTokens;
    Copy after login
    and introduce it in the trait

    array of the class:

    use HasApiTokens;
    Copy after login

    Now, we have successfully configured Laravel Passport.

  3. Create user authentication interface

    First, we need to create a controller to handle user authentication requests. You can execute the following command to generate a new controller:

    php artisan make:controller AuthController
    Copy after login
    Then, add the following method in AuthController

    to handle registration and login requests:
  4. use IlluminateHttpRequest;
    use IlluminateSupportFacadesAuth;
    
    class AuthController extends Controller
    {
     public function register(Request $request)
     {
         // 验证请求数据
         $request->validate([
             'name' => 'required|unique:users',
             'email' => 'required|email|unique:users',
             'password' => 'required|min:6'
         ]);
    
         // 创建用户
         $user = User::create([
             'name' => request('name'),
             'email' => request('email'),
             'password' => bcrypt(request('password')),
         ]);
    
         // 生成访问令牌
         $token = $user->createToken('accessToken')->accessToken;
    
         // 返回响应
         return response()->json(['token' => $token], 200);
     }
    
     public function login(Request $request)
     {
         // 验证请求数据
         $credentials = request(['email', 'password']);
    
         // 检查用户凭据
         if (!Auth::attempt($credentials)) {
             return response()->json(['message' => 'Unauthorized'], 401);
         }
    
         // 获取当前用户
         $user = $request->user();
    
         // 生成访问令牌
         $token = $user->createToken('accessToken')->accessToken;
    
         // 返回响应
         return response()->json(['user' => $user, 'token' => $token], 200);
     }
    }
    Copy after login

  5. Create RoutesOpen the routes/api.php

    file and add the following routes:
  6. Route::post('register', 'AuthController@register');
    Route::post('login', 'AuthController@login')->middleware('client');
    Copy after login

  7. Use Passport GuardOpen config/auth.php file, and change the api guard driver to passport

    :
  8. 'guards' => [
     'api' => [
         'driver' => 'passport',
         'provider' => 'users',
     ],
    ],
    Copy after login

  9. Use authenticated userNow, we can use the auth:api middleware to authenticate users and secure related API routes. For example, in AuthController

    , you can add the following route:

    public function profile()
    {
     $user = Auth::user();
    
     return response()->json(['user' => $user], 200);
    }
    Copy after login
    Then, in routes/api.php

    , add the following route:

    Route::get('profile', 'AuthController@profile')->middleware('auth:api');
    Copy after login
    In this way, when accessing the /api/profile route, the user will be asked to provide a valid authentication token first.


Summary:

This article details how to use Laravel Passport to implement PHP security verification. By installing and configuring Laravel Passport, we can quickly implement user authentication and authorization functions and protect our API routes. Hopefully this article will be helpful to developers using Laravel Passport for authentication. ###

The above is the detailed content of Implementing PHP security verification using Laravel Passport. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template