jwt laravel 常用方法
方法Auth防护实例提供以下方法。多个卫兵如果新创建的“api”防护未设置为默认防护,或者您已定义多个防护来处理身份验证,则应在调用auth()时指定防护。 $token = auth('api')->attempt($credentials);尝试()尝试通过某些凭据对用户进行身份验证。// Generate a token for the user if the credentials are valid$token = auth()->attempt($credentials);这将返回jwt或 null登录()记录用户并为其返回一个jwt。// Get some user from somewhere$user = User::first();// Get the token$token = auth()->login($user);用户()获取当前经过身份验证的用户。// Get the currently authenticated user$user = auth()->user();如果用户未经过身份验证,null则会返回。userOrFail()获取当前经过身份验证的用户或抛出异常。try { $user = auth()->userOrFail();} catch (\Tymon\JWTAuth\Exceptions\UserNotDefinedException $e) { // do something}如果未设置用户,则将Tymon\JWTAuth\Exceptions\UserNotDefinedException抛出a登出()将用户注销 - 这将使当前令牌无效并取消设置经过身份验证的用户。auth()->logout();// Pass true to force the token to be blacklisted "forever"auth()->logout(true);刷新()刷新令牌,使当前令牌无效$newToken = auth()->refresh();// Pass true as the first param to force the token to be blacklisted "forever".// The second parameter will reset the claims for the new token$newToken = auth()->refresh(true, true);无效()使令牌无效(将其添加到黑名单)auth()->invalidate();// Pass true as the first param to force the token to be blacklisted "forever".auth()->invalidate(true);tokenById()根据给定用户的ID获取令牌。$token = auth()->tokenById(123);有效载荷()获取原始JWT有效负载$payload = auth()->payload();// then you can access the claims directly e.g.$payload->get('sub'); // = 123$payload['jti']; // = 'asfe4fq434asdf'$payload('exp') // = 123456$payload->toArray(); // = ['sub' => 123, 'exp' => 123456, 'jti' => 'asfe4fq434asdf'] etc验证()验证用户的凭据if (auth()->validate($credentials)) { // credentials are valid}更高级的用法添加自定义声明$token = auth()->claims(['foo' => 'bar'])->attempt($credentials);明确设置标记$user = auth()->setToken('eyJhb...')->user();显式设置请求实例$user = auth()->setRequest($request)->user();覆盖令牌ttl$token = auth()->setTTL(7200)->attempt($credentials);