📜  laravel JWTAuthentication - PHP (1)

📅  最后修改于: 2023-12-03 15:32:33.503000             🧑  作者: Mango

Laravel JWT Authentication - PHP

Introduction

Laravel JWT Authentication is a package that enables JSON Web Token (JWT) authentication in Laravel applications. JWT is a standard for securely transmitting information between parties as a JSON object. Using JWT for authentication ensures that the client's identity is verified and secured.

Installation

To install Laravel JWT Authentication, run the following command in your terminal:

composer require tymon/jwt-auth

Once the package is installed, run the following commands to publish the config file and the secret key file:

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

php artisan jwt:secret
Configuration

The config file for JWT Authentication is located at config/jwt.php. Here you can configure various options such as the hashing algorithm, the token expiry time, the storage driver, and the user model.

Usage

To use JWT Authentication in your Laravel application, you can follow these steps:

  1. Create a login API route that accepts user credentials and returns a JWT token if the credentials are valid.

  2. Create a middleware that authenticates incoming requests using the JWT token.

  3. Protect your API routes using the middleware.

Generating Tokens

To generate a JWT token, you can use the attempt() method of the JWTAuth facade. This method accepts user credentials as an array and returns a token if the credentials are valid. Here is an example:

use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

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

        try {
            if (! $token = JWTAuth::attempt($credentials)) {
                return response()->json(['error' => 'invalid_credentials'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        return response()->json(compact('token'));
    }
}
Authenticating Requests

To authenticate incoming requests using the JWT token, you can create a middleware that checks for the token in the request headers and verifies it using the JWTAuth facade. Here is an example:

use Closure;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class VerifyJWTToken
{
    public function handle($request, Closure $next)
    {
        try {
            $token = JWTAuth::parseToken();
            if (! $token->authenticate()) {
                return response()->json(['error' => 'unauthorized'], 401);
            }
        } catch (JWTException $e) {
            return response()->json(['error' => 'invalid_token'], 400);
        }

        return $next($request);
    }
}
Protecting API Routes

To protect your API routes using the middleware, you can apply the middleware to the routes or to the controller. Here is an example:

use App\Http\Controllers\Controller;

class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('jwt.verify');
    }

    public function index()
    {
        // Your authenticated API code here
    }
}
Conclusion

Laravel JWT Authentication is a powerful package for securing your Laravel application's APIs. By implementing JWT authentication, you can ensure that your application is safe from unauthorized access and your users' data is protected.