Home >PHP Framework >Laravel >How to use jwt in laravel

How to use jwt in laravel

王林
王林Original
2023-05-21 10:40:071989browse

With the continuous development of APIs, more and more web applications need to use JSON Web Tokens (JWT) to implement user authentication and authorization. As a preferred framework for developing APIs, Laravel also supports JWT. This article will introduce how to use JWT in Laravel.

What is JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting claims as JSON objects between parties. JWT can be used for authorization, authentication and information exchange. JWT is usually transmitted as a Bearer token in the Authorization header of the HTTP request.

The structure of JWT consists of three parts: header, payload and signature. The header and payload are both JSON objects, and the signature is the encrypted result of combining these two parts. Since the structure of JWT is very simple, it can be easily parsed and verified.

How to use JWT in Laravel?

Using JWT requires installing the following dependent libraries in the Laravel project: tymondesigns/jwt-auth. In Laravel 5.7 and higher, you can use the following command to install the dependent library:

composer require tymon/jwt-auth

After the installation is complete, you need to add the following service provider and alias to the config/app.php file:

'providers' => [
    // Other Service Providers
    TymonJWTAuthProvidersLaravelServiceProvider::class,
],

'aliases' => [
    // Other Aliases
    'JWTAuth' => TymonJWTAuthFacadesJWTAuth::class,
    'JWTFactory' => TymonJWTAuthFacadesJWTFactory::class,
],

Next, you need to generate the JWT key. The key can be generated using the following command:

php artisan jwt:secret

This command will generate a random key and add it to the config/jwt.php file. It is important to protect this key and not disclose it to anyone.

After generating the key, you can start using JWT in Laravel. JWT can be used for authentication and authorization.

Authentication using JWT

The process for authenticating using JWT in Laravel is as follows:

  1. The user submits their credentials (for example, username and password).
  2. The application uses these credentials to generate a JWT and return it to the user.
  3. The user includes this JWT in the Authorization header as a Bearer token in subsequent requests.
  4. The application extracts user information from the JWT and verifies their identity.

The code to generate JWT and return it to the user is as follows:

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

    if (!$token = JWTAuth::attempt($credentials)) {
        return response()->json(['error' => 'Unauthorized'], 401);
    }

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

The code to verify the JWT and extract user information is as follows:

public function profile(Request $request)
{
    $user = JWTAuth::parseToken()->authenticate();

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

Use JWT for authorization

The process for using JWT for authorization in Laravel is as follows:

  1. The application verifies the user's identity before they access protected resources.
  2. If the user has been authenticated, the application checks that the JWT contains the appropriate roles or permissions.
  3. If the user has the appropriate role or permission, the application grants the user access to the requested resource.

The code to verify the JWT and check the user's role or permissions is as follows:

public function index(Request $request)
{
    $user = JWTAuth::parseToken()->authenticate();

    if ($user->hasRole('admin')) {
        $items = Item::all();
    } else {
        $items = Item::where('user_id', '=', $user->id)->get();
    }

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

It should be noted that the hasRole() method here is a custom method and needs to be in the User model accomplish.

Summary

This article introduces the process of using JWT for authentication and authorization in Laravel. JWT provides a secure, simple, and scalable user authentication mechanism that protects applications from a variety of attacks. If you are developing a web application that requires an API, using JWT is a good choice.

The above is the detailed content of How to use jwt in laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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