Trong bài viết này, chúng ta sẽ cùng tìm hiểu và triển khai token JWT trong nhiều ngôn ngữ lập trình nhé!
NodeJS
Phiên bản yêu cầu tối thiểu: 8.0.0
Link thư viện: https://www.npmjs.com/package/jsonwebtoken
Khai báo thư viện:
const jwt = require("jsonwebtoken");
JavaScriptTạo token:
var token = jwt.sign({ foo: 'bar' }, "mậtkhẩu");
JavaScriptVerify token:
try {
var json = jwt.verify(token, "mậtkhẩu");
} catch(err) {
// err
}
JavaScriptC# (.Net)
Phiên bản yêu cầu tối thiểu: .Net 6.0, .Net Standard 1.3, .Net Framework 3.5
Link thư viện: https://www.nuget.org/packages/JWT
Khai báo thư viện:
using JWT.Algorithms;
using JWT.Builder;
using JWT.Exceptions;
C#Tạo token:
JwtBuilder tokenBuilder = JwtBuilder.Create();
tokenBuilder.WithAlgorithm(new HMACSHA256Algorithm()).WithSecret("mậtkhẩu");
tokenBuilder.AddClaim("user_id", 1)
.AddClaim("iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds())
.AddClaim("exp", DateTimeOffset.UtcNow.AddDays(1).ToUnixTimeSeconds());
string token = tokenBuilder.Encode();
C#Verify token:
try
{
JwtBuilder jsonBuilder = JwtBuilder.Create();
jsonBuilder.WithAlgorithm(new HMACSHA256Algorithm()).WithSecret("mậtkhẩu");
jsonBuilder.MustVerifySignature();
string json = jsonBuilder.Decode(token);
}
catch (Exception ex)
{
switch (ex)
{
case InvalidTokenPartsException:
case TokenNotYetValidException:
Console.WriteLine("Token is not valid yet");
break;
case TokenExpiredException:
Console.WriteLine("Token has expired");
break;
case SignatureVerificationException:
Console.WriteLine("Token has invalid signature");
break;
default: throw;
}
}
C#PHP
Phiên bản yêu cầu tối thiểu: 8.x
Link thư viện: https://github.com/firebase/php-jwt
Khai báo thư viện:
include_once 'vendor/autoload.php';
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
PHPTạo token:
$payload = [
'user_id' => 123,
'iat' => time(),
];
$token = JWT::encode($payload, 'mậtkhẩu', 'HS256');
PHPVerify token:
try {
$jsonText = JWT::decode($token, new Key('mậtkhẩu', 'HS256'));
} catch (SignatureInvalidException $e) {
// provided JWT signature verification failed.
} catch (BeforeValidException $e) {
// provided JWT is trying to be used before "nbf" claim OR
// provided JWT is trying to be used before "iat" claim.
} catch (ExpiredException $e) {
// provided JWT is trying to be used after "exp" claim.
} catch (UnexpectedValueException $e) {
// stuff
}
PHP