markdown Laravel中的JWT设置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Laravel中的JWT设置相关的知识,希望对你有一定的参考价值。

# JWT Setup in Laravel

## Installation

Type in CLI

**composer require tymon/jwt-auth**

## Add providers in config/app.php

In Providers array add

**Tymon\JWTAuth\Providers\LaravelServiceProvider::class**

In Aliases array add

**'JWTAuth'=>Tymon\JWTAuth\Facades\JWTAuth::class** (optional)

## Publish config file and generate secret key

Type in CLI

**php artisan vendor:publish "Tymon\JWTAuth\Providers\LaravelServiceProvider::class"**

Then a jwt.php file should be found in config directory

**php artisan jwt:secret** to generate a secret key

## Modify the User.php Model

Add **use Tymon\JWTAuth\Contracts\JWTSubject**

Make sure the User class implements the JWTSubject class then add the following methods:

```
public function getJWTIdentfier()
{
  return $this->getKey();
}

public function getJWTCustomClaims()
{
  return []; 
}

```

## Exception Handling

**use Tymon\JWTAuth\Exceptions\JWTException**

## Sample Login using JWT

```
public function login(Request $request)
{
  // Some input validation logic here
  
  $credentials = $request->only(['email','password']);
  
  try {
    if(!$token = auth()->attempt($credentials)) {
      return response()->json(['error'=>'Invalid email or password.'], 401);
    }
  } catch(JWTException $e) {
    return response()->json(['error'=> $e->getMessage()], 500);
  }
  
  return response()->json(['token'=> $token], 200);
  
  // You can add redirect logic in here just make sure to save the token
}

```

## Setup Middleware in app/Http/Middleware/Kernel.php under $routeMiddleware array
**'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class**

**'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class**


以上是关于markdown Laravel中的JWT设置的主要内容,如果未能解决你的问题,请参考以下文章

LARAVEL WEB API 中的 JWT 或 OAuth 或两者

无法从 laravel 5 应用程序中的请求中解析 jwt 令牌

Laravel JWT API 令牌处理

如何使用 Laravel 5 设置 JWT-Auth

Laravel 未检测到标头和 JWT 包中发送的身份验证令牌

AdonisJs / Laravel 中的 JWT 令牌验证过程