01
/JWTを生成します。
/**
* Demo program for generating JWT (JSON Web Token).
*/
const jwt = require('jsonwebtoken');
const TOKEN_SIGNING_OPTIONS = {
algorithm: 'HS256',
};
const userId = 'MyUserID';
const accessKey = 'my-access-key';
const secretKey = 'my-secret-key';
// seconds
const validDuration = 60 * 30;
const payload = {
exp: Math.floor(Date.now() / 1000) + validDuration,
iss: userId,
accessKey,
};
const encodedJWT = jwt.sign(payload, secretKey, TOKEN_SIGNING_OPTIONS);
console.log(`JWT:${encodedJWT}`);
02
/JWTでAPIリクエストを送信します。
/**
* Demo prorgram of authentication by JWT.
*/
const fetch = require('node-fetch');
const token = 'my-jwt';
const sampleRequest = async () => {
const url = 'https://translate.rozetta-api.io/api/v1/hello';
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});
const responseJSON = await response.json();
console.log(responseJSON);
};
sampleRequest();