我使用的是JWT网络令牌系统。我成功地生成了TOKENS。我正在Laravel中创建JWT代币,如下
我正在使用以下技术堆栈
- LARAVEL 5.2框架
- JWT(套装)
样本代码
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'));
}
}
样本输出
我得到
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ
问题1
生成的令牌是唯一的吗
JWT是唯一的,没有两个相同的用户可以为他们生成相同的令牌
一般来说,JWT实际上是在替换用户名和密码的组合。这意味着,服务器将在用户第一次登录时验证凭据是否正确后返回一个唯一的令牌,而不是为每个限制资源的请求不断发送用户名和密码。之后,每个请求都将包括令牌,在完成请求之前,令牌将被检查为有效或无效。
因此,如果两个用户使用两个有效凭据登录,它将从服务器接收两个不同的令牌。