从零开始系列-Laravel编写api服务接口:3.JWT多用户访问

Laravel框架
455
0
0
2022-04-12
标签   Laravel授权

jwt (json web token)

简介

jwt 就不说了,是一种普遍的后端 api 授权方式,这个写完之后再写一个go版本和java版本的 :) 闲话少叙,怎么实现一个多用户认证呢,下面开始。

github.com/tymondesigns/jwt-auth

文档 jwt-auth.readthedocs.io/

需求:

有一个用户表,一个管理员表,要求用户和管理员都可以登陆并且查看或者审核文章,做一个登陆接口获取token并且验证token

下面开始:

  1. 开始安装

composer require tymon/jwt-auth

  1. 发布配置文件
  2. php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
  3. 用命令生成jwtkey
# 这条命令会在 .env 文件下生成一个加密密钥,如:JWT_SECRET=xadsfasdf
php artisan jwt:secret
  1. 进行一些配置

由于要用到多用户配置所以要配置多个模型

php artisan make:model User

php artisan make:model Admin

User.php 代码如下:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject // 必须实现JWTSubject接口
{
    use HasFactory, Notifiable;


    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier(){
         return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */ 
     public function getJWTCustomClaims(){
        return [];
     }
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = ['id'];
}

Admin.php 代码如下:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Tymon\JWTAuth\Contracts\JWTSubject;

class Admin extends Model implements JWTSubject
{
    use HasFactory;


    /**
     * @inheritDoc
     */ 
    public function getJWTIdentifier(){
        return $this->getKey();
    }

    /**
     * @inheritDoc
     */ 
     public function getJWTCustomClaims(){
        return [];
     }
}

打开config/auth.php文件改为如下:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */ 

    'defaults' => ['guard' => 'web','passwords' => 'users',],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */ 

    'guards' => ['web' => ['driver' => 'session','provider' => 'users',],

        'user' => ['driver' => 'jwt','provider' => 'users','hash' => false,],'admin' => ['driver' => 'jwt','provider' => 'admins','hash' => false,],],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */ 

    'providers' => ['users' => ['driver' => 'eloquent','model' => App\Models\User::class,],'admins' => [// key 对应上面的guards里面对应的 provider 'driver' => 'eloquent','model' => App\Models\Admin::class, // 这个模型继承了jwtSubject接口],],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */ 

    'passwords' => ['users' => ['provider' => 'users','table' => 'password_resets','expire' => 60,'throttle' => 60,],],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */ 

    'password_timeout' => 10800,

];
  1. 编写登陆接口

多说一句多端登陆接口一般都是通用的,可以放在各模块下,也可以用公共模块,此处用统一登陆接口

新建登陆控制器(此处用的是restfull api的控制器结构,你可以去掉–resource)

php artisan make:controller V1\common\AuthorizationController --resource

AuthorizationController.php 方法下放入以下代码:

记得在app\Http\Controllers\Controller.php里面use helpers;就是 dingo 扩展文件

<?php

namespace App\Http\Controllers;

use Dingo\Api\Routing\Helpers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;use Helpers; // 应用dingo的helpers
}
    <?php

namespace App\Http\Controllers\V1\common;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthorizationController extends Controller
{

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */ 
    public function store(Request $request){
        $guard = $request->guard;// 区分是user还是admin type就是guard
        if (!config('auth.guards.' . $guard)) {
            return $this->response->errorUnauthorized('用户类型不存在');
        } 
        $credentials = []; // 登陆验证字段
        switch ($guard) {
            case 'user':  
                $credentials = $request->only(['email', 'password']);
                break;
           case 'admin':
                $credentials = $request->only(['account', 'password']);
                break;
        }
        $token = auth($guard)->attempt($credentials);
        if (!$token){
            return $this->response()->errorUnauthorized('账号或密码错误');
        }
        return $this->respondWithToken($token,$guard); // type就是guard
     }


    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me(){
        return $this->user();// 一般用auth($guard)->user();至于如何用this需要再中间件里面处理详情请看第`5`章
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */ 
    public function logout($guard){
        auth($guard)->logout();

        return $this->response()->array(['message' => '退出登陆']);
    }

    /**
     * Refresh a token.
     * 刷新token,如果开启黑名单,以前的token便会失效。
     * 值得注意的是用上面的getToken再获取一次Token并不算做刷新,两次获得的Token是并行的,即两个都可用。
     * @return \Illuminate\Http\JsonResponse
     */ 
    public  function refresh($guard){
        return $this->respondWithToken(auth($guard)->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */ 
    protected function respondWithToken($token, $guard){
        return response()->json(['access_token' => $token,'token_type' => 'bearer','expires_in' => auth($guard)->factory()->getTTL() * 60]);
    }

}

新增登陆路由文件:

// 公共路由
$api->group(['as' => 'common', 'prefix' => 'common', 'namespace' => 'Common', 'middleware' => []], function ($api) {// 登录获取token   
    $api->post('authorization', 'AuthorizationController@store')->name('.authorizations.store');
});

访问:

email:hansen.idella@example.com
guard:user
password:123456

homestead.test/api/common/authoriza...

传入对应参数,就可以了

{"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ob21lc3RlYWQudGVzdFwvYXBpXC9jb21tb25cL2F1dGhvcml6YXRpb24iLCJpYXQiOjE2MTAwOTg0NDUsImV4cCI6MTYxMDEwMjA0NSwibmJmIjoxNjEwMDk4NDQ1LCJqdGkiOiJzYkFFZXdJbzFLWjZrU0IyIiwic3ViIjoxLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.61tRyGj-iD3-rEzLti1GLzgCJ35of_88-4-R0PQi_5E","token_type": "bearer","expires_in": 3600
}

传入:

guard:admin
password:123456
account:38129

返回

{"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9ob21lc3RlYWQudGVzdFwvYXBpXC9jb21tb25cL2F1dGhvcml6YXRpb24iLCJpYXQiOjE2MTAzNTM5MjUsImV4cCI6MTYxODEyOTkyNSwibmJmIjoxNjEwMzUzOTI1LCJqdGkiOiJLNW1ZenZsOEY3N1A0azl0Iiwic3ViIjoxLCJwcnYiOiJkZjg4M2RiOTdiZDA1ZWY4ZmY4NTA4MmQ2ODZjNDVlODMyZTU5M2E5In0.NYZKW2wbfMPAjLF-d-oA88OMrCNo8WHy7wAM_zhxlzU","token_type": "bearer","expires_in": 7776000
}

另外配置jwt文件:

.env文件下面加上

# jwt
JWT_SECRET=VN3L60yj9zjcwwX0W70Ep6grzOlFe5QE
JWT_TTL=129600 #3 * 30 * 24 * 60 #token过期时间 单位为分钟 3个月
JWT_REFRESH_TTL=20160 #刷新token过期时间 单位为分钟
JWT多用户鉴权已经全部完成,是不是很简单?