lumen中安装使用jwt

Tymon/jwt-auth

Installation
composer require tymon/jwt-auth

This service provider must be registered.

Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class,

Add this to your aliases

'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class

To publish the config settings in Laravel 5 use

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

Don’t forget to set a secret key in the config file!

php artisan jwt:generate

Add Middleware

'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,

For Lumen

This service provider must be registered.

$app->register(Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);

Add Facade To Bootstrap App.php

$app->withFacades(true,[
...
    'Tymon\JWTAuth\Facades\JWTAuth'             => 'JWTAuth',
    'Tymon\JWTAuth\Facades\JWTFactory'          => 'JWTFactory'
]);

Add Middleware To Bootstrap App.php

$app->routeMiddleware([
....
    'jwt.auth'    => Tymon\JWTAuth\Middleware\GetUserFromToken::class,
    'jwt.refresh' => Tymon\JWTAuth\Middleware\RefreshToken::class,
]);
Error

Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Cache\CacheManager
Dependency Bind from

$app->bind(Illuminate\Cache\CacheManager::class, function ($app) {
    return new Illuminate\Cache\CacheManager($app);
});

Unresolvable dependency resolving [Parameter #0 [ $app ]] in class Illuminate\Auth\AuthManager

$app->bind(Illuminate\Auth\AuthManager::class, function ($app) {
    return new Illuminate\Auth\AuthManager($app);
});

Examples

use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

$date=['name'=>'root','password'=>'123456',];

$token=\JWTAuth::attempt($date,['driver'=>'ios']);
//dd(\JWTAuth::toUser($token)->toArray());
//dd(\JWTAuth::getPayload($token)->toArray());
try{
    dd (\JWTAuth::authenticate($token)->toArray());
}catch(JWTException $e){
    dd($e->getStatusCode()."--".$e->getMessage()."--line:".$e->getLine()."--".$e->getFile());
}

For Lumen

$this->validate($request, [
    'mobile' => 'required|digits:11',
    'password' => 'required',  
]);
$mobile=$request->input('mobile');
$password=$request->input('password');
$user=User::where('mobile',$mobile)->first();
if ($user&&Hash::check($password, $user->password)){
    try {
        $token=JWTAuth::fromUser($user);//['driver']
        return response()->json(compact('token'));
    }catch (JWTException $e){
        return $e->getStatusCode()."--".$e->getMessage()."--line:".$e->getLine()."--".$e->getFile();
    }
}else{
    return response()->json(['error'=>'1001']);
}

转载于:https://my.oschina.net/zwyang/blog/917652

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值