1// Import the module
2import jwt from "jsonwebtoken";
3
4// You will need a SECRET KEY to create the token, I would recommend to store
5// it inside a .env file. For this example though, I will store it a variable.
6const secretKey = "ro8BS6Hiivgzy8Xuu09JDjlNLnSLldY5";
7
8// Data that will be stored inside the token. In this example we will store the
9// name and the role of each user
10var payload = {
11 name: "Roger",
12 role: "Admin",
13};
14
15// Generate the token
16const token = jwt.sign(payload, secretKey);
17
18// The token is ready to send to the client. REST API example:
19res.status(200).send(JSON.stringify({ accessToken: token }));
20
21// Client will store your token the following way: "Bearer " + token
22
23// How to decode a user's token and get its payload. REST API example:
24const authHeader = req.headers["authorization"]; // Client will send you back the token inside request's authorization header
25
26const token = authHeader && authHeader.split(" ")[1];
27if (token == null) {
28 res.status(401).send(); // Unauthorized
29}
30
31var decoded = jwt.verify(token, secretKey, (err, user) => {
32 if (err) {
33 res.status(403).send(); // Forbidden
34 }
35});
36
37// Do what you want to do with the data
38
39// Remember that this is for learning purposes only. You should create FUNCTIONS
40// AND MIDDLEWARES so you do not repeat code.
41
1app.post('/profile', passport.authenticate('jwt', { session: false }),
2 function(req, res) {
3 res.send(req.user.profile);
4 }
5);
6
1JSON Web Token is an Internet standard for creating data with optional
2signature and/or optional encryption whose payload holds JSON that asserts
3some number of claims.
4
5The tokens are signed either using a private secret or a public/private key.
1apiRoutes.post('/', function (req, res) {
2if (req.body.UserName != "tadriano" || req.body.PassWord != "102030") {
3 res.json({ success: false, message: 'Usuário ou senha incorreto(s)!' });
4} else {
5let usuario = new user()
6 {
7 name : "tadriano";
8 admin: true
9 };
10var token = jwt.sign(usuario, 'batman batman batman', {
11 expiresInMinutes: 1440
12 });
13
14 res.json({
15 success: true,
16 message: 'Token criado!!!',
17 toke: token
18 });
19 }
20});
1Dim PrivateKey As String = "MIIEowIBAAKCAQEAjtTe7UUP/CBI9s...BLABLABLA...JfwZ2hHqFPXA9ecbhc0".Replace(vbLf, "").Replace(vbCr, "")
2
3Dim ar1 As JObject = New JObject()
4ar1.Add("typ", "JWT")
5ar1.Add("alg", "RS256")
6
7Dim header As String = Base64UrlEncoder.Encode(ar1.ToString)
8
9Dim ar2 As JObject = New JObject()
10ar2.Add("iss", "INTEGRATION_ID")
11ar2.Add("sub", "GUID_VERSION_OF_USER_ID")
12ar2.Add("iat", DateDiff(DateInterval.Second, New Date(1970, 1, 1), Now().ToUniversalTime))
13ar2.Add("exp", DateDiff(DateInterval.Second, New Date(1970, 1, 1), DateAdd(DateInterval.Hour, 1, Now().ToUniversalTime)))
14ar2.Add("aud", "account-d.docusign.com")
15ar2.Add("scope", "signature")
16
17Dim body As String = Base64UrlEncoder.Encode(ar2.ToString)
18
19Dim stringToSign As String = header & "." & body
20
21Dim bytesToSign() As Byte = Encoding.UTF8.GetBytes(stringToSign)
22
23Dim keyBytes() As Byte = Convert.FromBase64String(PrivateKey)
24
25Dim privKeyObj = Asn1Object.FromByteArray(keyBytes)
26Dim privStruct = RsaPrivateKeyStructure.GetInstance(privKeyObj)
27
28Dim sig As ISigner = SignerUtilities.GetSigner("SHA256withRSA")
29
30sig.Init(True, New RsaKeyParameters(True, privStruct.Modulus, privStruct.PrivateExponent))
31
32sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length)
33Dim signature() As Byte = sig.GenerateSignature()
34
35Dim sign As String = Base64UrlEncoder.Encode(signature)
36
37Return header & "." & body & "." & sign
38