1:首先通过composer进行安装

composer require tymon/jwt-auth

2:添加服务提供者

编辑 config/app.php,在 “providers” 添加:

‘tymon\jwtauth\providers\jwtauthserviceprovider’,

3:添加 facades

编辑 config/app.php,在 “alias” 添加:

‘jwtauth’ => ‘tymon\jwtauth\facades\jwtauth’,

‘jwtfactory’ => ‘tymon\jwtauth\facades\jwtfactory’,

4:发布配置文件:

php artisan vendor:publish –provider=”tymon\jwtauth\providers\jwtauthserviceprovider”

5:生成 secret key

: php artisan jwt:generate

安装完成后,执行 php artisan jwt:generate,会报错:

(1).method tymon\jwtauth\commands\jwtgeneratecommand::handle() does not exist

解决方法,这个需要修改源码:

编辑 vendor/tymon/jwt-auth/src/commands/jwtgeneratecommand.php,新增:

 /**
 * compatiblity with laravel >= 5.5
*/
 public function handle()
 {
  $this->fire();
 }

(2)如果未添加服务提供者,直接执行该命令,可能也会报错!

there are no commands defined in the “jwt” namespace

解决方法:

就是上面的添加服务提供者

配置(configuration)

secret(secret key) – 秘钥

用来签名 token 的秘钥。作者将秘钥与 laravel 的 app_key 分开,以便开发者可以独立地修改它们。

提供了一个 artisan 命令,为我们生成一个随机秘钥。(php artisan jwt:generate)

ttl(token time to live) – token 生存时间

token 的有效时间,以分钟为单位。建议尽可能设置短点,尤其是当我们也使用 token 刷新机制。

refresh_ttl(refresh time to live) – refresh 生存时间

可以刷新 token 的有效时间,以分钟为单位。例如,如果设置为 2周,那么只能在 2周 内,刷新对应的 token,否则将会抛出 tokenexpiredexception 异常。如果超过了刷新的有效时间,必须生成一个全新的 token,这意味着用户需要重新登录。

注:ttl 和 refresh_ttl,用于保持用户的登录状态

algo(hashing algorithm) – hash 算法

用于签名 token 的算法,保留默认值即可

user(user model path) – 用户模型路径

应该指向我们项目的 user 类的命名空间路径

identifier(user identifier) – 用户标识

从 token 的主题声明中,根据什么标识来检索用户(一般是 id)

required_claims(required claims)

这些声明必须存在于 token 的 payload 中,否则将抛出 tokeninvalidexception 异常(会检测 token 的 payload 是否存在这些声明)

blacklist_enabled(blacklist enabled)

如果设置为 false,将无法使 token 失效。虽然我们仍然可以刷新令牌,但是之前的令牌仍旧有效,因此这样做非常不安全。但对于非常简单的实现,可能不需要额外的开销(刷新 token 等),我们可以配置它。

providers

jwt-auth 包已经有一些具体实现,可用来实现各种需求。只要遵循相关接口,我们就可以覆盖这些具体实现。

providers.user

指定基于主题声明,来查找用户的实现。

providers.jwt

完成 token 的编码和解码的繁重工作

providers.auth

通过凭证或 id 来认证用户

providers.storage

用于驱动黑名单,并存储 token 直到过期。

创建 tokens(creating tokens)

jwt-auth 包为我们提供了创建 token 的多种方法。有简单的方法,如果你想更好的控制,也有更进一步的方法。

开箱即用(out of box),有许多必须的声明,虽然这些都可以配置:

sub(subject) – 包含 token 的标识符(默认是用户 id)

iat(issued at) – token 发布时间(unix 时间戳)

exp(expiry) – token 过期日期(unix 时间戳)

nbf(not before) – 可以使用 token 的最早时间点(unix 时间戳)

iss(issuer) – token 发布者(默认为请求的 url)

jti(jwt id) – token 的唯一标识符(sub 和 iat 声明的 md5 值)

aud(audience) – token 的目标受众(默认不需要)

也允许自定义声明。稍后会介绍。

创建一个基于用户凭证的 token

创建 token 的最常用方法是,通过用户的登录凭证,来认证用户。如果认证成功,则返回一个与该用户相关的 token。例如,假设我们有一个 laravel authenticatecontroller

use jwtauth;
use tymon\jwtauth\exceptions\jwtexception;
 
class authenticatecontroller extends controller
{
 public function authenticate(request $request)
 {
  // grab credentials from the request
  $credentials = $request->only('email', 'password');
 
  try {
   // attempt to verify the credentials and create a token for the user
   if (! $token = jwtauth::attempt($credentials)) {
    return response()->json(['error' => 'invalid_credentials'], 401);
   }
  } catch (jwtexception $e) {
   // something went wrong whilst attempting to encode the token
   return response()->json(['error' => 'could_not_create_token'], 500);
  }
 
  // all good so return the token
  return response()->json(compact('token'));
 }
}

创建一个基于用户对象的 token

我们可以跳过用户认证,只传递一个用户对象

$user = user::first();
$token = jwtauth::fromuser($user);

上面的 2 个方法也有第二个参数,可以传递一个 ‘自定义声明’ 的数组

在解码 token 时,这些自定义声明,将和其他声明一起提供。

注意:添加大量的自定义声明,将增加 token 的大小

创建一个基于任意你喜欢的内容的 token

作者给我们提供了对底层类和方法的访问,来提供高级的、可自定义的功能。

示例使用了内建的 ‘tymon\jwtauth\payloadfactory’ 实例(或者使用 jwtfactory 门面):

$customclaims = ['foo' => 'bar', 'baz' => 'bob'];
$payload = jwtfactory::make($customclaims);
$token = jwtauth::encode($payload);

也可以在 ‘tymon\jwtauth\payloadfactory’ 实例上链式调用声明(或者使用 jwtfactory 门面):

$payload = jwtfactory::sub(123)->aud('foo')->foo(['bar' => 'baz']);
$token = jwtauth::encode($payload);

认证(authentication)

一旦用户使用他们的凭证登录,下一步将使用 token 发起一个后续请求,来检索用户详情,以便我们可以将其显示为已登录。

使用内置方法,通过 http 发起认证请求,我们需要设置一个 authorization 请求头,如下所示:

authorization: bearer {yourtokenhere}

apache 用户需要注意:

apache 好像会丢弃 authorization 请求头,如果该请求头不是 base64 编码的 user/pass 组合。为了解决此问题,我们可以在 apache 配置文件中添加一下内容:

 rewriteengine on
  rewritecond %{http:authorization} ^(.*)
  rewriterule .* - [e=http_authorization:%1]

或者,我们可以通过在查询字符串中包含 token 来实现:

http://api.mysite.com/me?token={yourtokenhere}

为了从请求中获取 token,我们可以:

// 会设置 token 到返回的对象中
jwtauth::parsetoken();
// 接着,我们可以继续链式调用方法
$user = jwtauth::parsetoken()->authenticate();

为了获取 token 的值,我们可以调用:

$token = jwtauth::gettoken();

如果设置了一个 token,则会返回 token,否则(为方便起见),它将使用上述方法,尝试从请求中解析 token,如果没有设置 token 或 没有 token 可以被解析,最终返回 false。

当然,如果在我们的程序中有其他入口点,我们也可以根据需要手动设置 token。例如:

jwtauth::settoken('foo.bar.baz');

从 token 中检索认证过的用户

public function getauthenticateduser()
  {
   try {
    if(! $user = jwtauth::parsetoken()->authenticate()){
     return response()->json('user_not_found', 404);
    }
   } catch (tymon\jwtauth\exceptions\tokenexpiredexception $e) {
    return response()->json(['token_expired'], $e->getstatuscode());
   } catch (tymon\jwtauth\exceptions\tokeninvalidexception $e) {
    return response()->json(['token_invalid'], $e->getstatuscode());
   } catch (tymon\jwtauth\exceptions\jwtexception $e) {
    return response()->json(['token_absent'], $e->getstatuscode());
   }
   return response()->json(compact('user'));
  }

如果不喜欢内联捕获多个异常的方法,我们可以随意使用 laravel 添加全局异常处理程序。

在 app/exceptions/handler.php 中,将下面代码添加到 render() 方法:

 public function render($request, exception $e)
  {
   if ($e instanceof tymon\jwtauth\exceptions\tokenexpiredexception) {
    return response()->json(['token_expired'], $e->getstatuscode());
   } else if ($e instanceof tymon\jwtauth\exceptions\tokeninvalidexception) {
    return response()->json(['token_invalid'], $e->getstatuscode());
   }
 
   return parent::render($request, $e);
  }

中间件和过滤器

如果我们使用的是 laravel 5,可以使用内置的 2 个中间件:

getuserfromtoken

检查请求头和查询字符串(正如上面解释过的)是否存在 token,并尝试解码 token。如上所述,同样的事件被触发。

refreshtoken

此中间件将再次尝试从请求中解析 token,然后将刷新 token(从而使旧 token 失效),并将其作为下一次响应的一部分返回。这实际上产生了单个使用 token 流,如果 token 被泄露,这种方式会减少攻击,因为它仅对单个请求有效。

为了使用这 2 个中间件,我们需要将它们注册到 app/http/kernel.php 里的 $routemiddleware 属性:

 protected $routemiddleware = [
    ...
    'jwt.auth' => 'tymon\jwtauth\middleware\getuserfromtoken',
    'jwt.refresh' => 'tymon\jwtauth\middleware\refreshtoken',
   ];

以上这篇laravel5.5安装jwt-auth 生成token令牌的示例就是www.887551.com分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持www.887551.com。