如何从 Laravel 的请求中获取 Bearer 令牌

2022-01-10 00:00:00 jwt php laravel

我期望来自所有传入请求的 JWT 令牌,它应该包含在请求标头中,例如:Authorization =>;'Bearer:这里有一些令牌'

I am expecting a JWT token from all the incoming request, and it should be included on request headers like: Authorization => 'Bearer: some token here'

我想得到这个令牌并验证它:这是我正在尝试的:

I want to get this token and verify it: here is what I am trying:

$token = $request->header('Authorization');

这就是我得到的:

<代码> 授权:承载:eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJleGFtcGxlLm9yZyIsImF1ZCI6ImV4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDB9.UQUJV7KmNWPiwiVFAqr4Kx6O6yd69lfbtyWF8qa8iMN2dpZZ1t6xaF8HUmY46y9pZN76f5UMGA0p_CMqymRdYfNiKsiTd2V_3Qpt9LObaLg6rq18j3GLHfdr8nyBzO3v7gTpmNaU6Xy47aMDsbcs593Lx_lD3PnO41oEHgih7CsRKW1WcW1radnpEhdDO7-GpmGOF6xUnpAlQ9EHqpqnIlZPbVoJg92Iwozn-07uuWrkyKUpYN4IPpstd1ks3cKlJ6FH-2ROiC4N0MVLxp4lhUyKhLdwgDWYH4tjtdrEVK0a3_zVtK1ukvriEJqMkfYHnE6Bwv_pv_-lRNy_y7m-YQ"

问题有没有办法只获取不包括Authorization: Bearer"的令牌当然我可以解析整个字符串并获取令牌,但我只是想知道是否有另一种方法可以在不解析的情况下获取它.

Question is there any way to grab only the token not including "Authorization: Bearer" and of course I could parse the whole string and get the token, but I am just wondering if there is another way of getting it without parsing.

推荐答案

IlluminateHttpRequest对象上有一个bearerToken()方法,所以你应该能够只做 $token = $request->bearerToken(); 并得到你所期望的(在 Laravel 5.5 中 - 我不确定以前的版本).

There is a bearerToken() method on the IlluminateHttpRequest object, so you should be able to just do $token = $request->bearerToken(); and get back what you expect (that's in Laravel 5.5 - I'm not sure of previous versions).

相关文章