【发布时间】:2015-05-14 21:34:41
【问题描述】:
我有一个 laravel 5 后端,它在使用 jwt-auth 登录时将 jwt-token 作为 json 响应发送。
现在我想将用户角色添加到laravel发送的jwt令牌中,我尝试了以下方式:
这是我当前的控制器
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Database\Eloquent\Model;
use App\User;
class AuthenticateController extends Controller
{
public function authenticate(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
$user = User::where('email', '=', $credentials['email'])->first();
$customClaims = ['role' => $user->role];
try {
// attempt to verify the credentials and create a token for the user
if (! $token = JWTAuth::attempt($credentials, $customClaims)) {
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'));
}
}
?>
有没有更干净的方法来做到这一点?
【问题讨论】:
-
JWT for php 的文档记录不佳。做一个简单的登录/注销系统是痛苦的!看看我的问题。
-
我也在找同样的东西,你找到解决办法了吗?
-
我选择了上面的解决方案,即使它是另外一个查询。找不到更清洁的解决方案
-
您可以根据自己的喜好创建令牌。它不必是用户或一组权限。 github.com/tymondesigns/jwt-auth/wiki/… 所以我认为最好在你的模型或存储库上设置这个登录名并调用它?