当Laravel用作客户端时

当Laravel用作客户端时

本文介绍了当Laravel用作客户端时,将JWT存储在哪里以进行身份​​验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Laravel 6和GuzzleHTTP 7.

我可以设法向外部(REST-)API发出请求,并成功授权并取回令牌:

{"&的access_token QUOT;:" FooXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjExNjkyNDQsImlhdCI6MTYxODU3aNzI0NCwibmJmIjoxNjE4NTc3MjQ0LCJpZGVudGl0eSI6MTQzfQ.wdDzVbE-5O8mfsIqzNvXFpv7THkYYp522HMpyEc8LX0BAR"}

我是否必须在会话中显式保存此令牌?我正在尝试在以下所有对外部API的请求中使用此令牌.

通过谷歌搜索,我只找到了有关Laravel如何生成JWT的教程,但是没有找到当Laravel用作客户端并请求JWT时如何进行的教程.

任何帮助,不胜感激!

更新:Laravel APP本身就是客户端(无论用户在内部" Laravel中).

解决方案

从第三方服务获取令牌后,将其存储在某种形式的存储中(例如文件,数据库,缓存).我建议使用缓存,因为它更快(如果您使用内存缓存,如Redis),则可以设置TTL.

如果令牌在特定时间段后过期,并且没有刷新令牌,则将TTL设置为该日期/时间.

示例:

  $ ttl = Carbon :: now()-> addHour();//设置为过期时间;如果令牌未过期,则设置为null$ jwtToken = Cache :: remember('fooServiceJwtToken',$ ttl,function(){$ jwt = getJwtTokenUsingGuzzle();//改变返回$ jwt;}); 

请勿将数据存储在会话中,因为会话是使用您的应用程序绑定到用户的.

I use Laravel 6 and GuzzleHTTP 7.

I could manage to make a request to an external (REST-) API and successfully authorize and get a token back:

{"access_token":"FooXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjExNjkyNDQsImlhdCI6MTYxODU3aNzI0NCwibmJmIjoxNjE4NTc3MjQ0LCJpZGVudGl0eSI6MTQzfQ.wdDzVbE-5O8mfsIqzNvXFpv7THkYYp522HMpyEc8LX0BAR"}

Do I have to save this token explicitly in a session?I'm trying to use this token in every following requests to the external API.

By googling I found only tutorials for Laravel how to generate JWT but not how to proceed when Laravel is used as a client and requests JWT.

Any help much appreciated!

UPDATE: The Laravel APP itself is the client (regardless of the user "inside" Laravel).

解决方案

Upon getting your token from a 3rd party service, store it in some form of storage (e.g. file, database, cache). I recommend using a Cache, as it's faster (if your using an in-memory cache like Redis), and you can set a TTL.

If the token expires after a certain period of time, and doesn't have a refresh token, then set the TTL to that date/time.

Example:

$ttl = Carbon::now()->addHour(); // set to when it expires or null if token doesn't expire
$jwtToken = Cache::remember('fooServiceJwtToken', $ttl, function () {
    $jwt = getJwtTokenUsingGuzzle(); // CHANGE
    return $jwt;
});

Do not store the data in a session, as sessions are tied to users using your application.

这篇关于当Laravel用作客户端时,将JWT存储在哪里以进行身份​​验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 04:54