postman 从base64生成访问报头

zzzyeukh  于 2023-03-18  发布在  Postman
关注(0)|答案(1)|浏览(244)

对于每个API请求,需要修改头,我有一个来自Postman的预请求脚本,如下所示:

var Authentication = "";
Authentication += pm.collectionVariables.get( "TokenHead" );
Authentication += "." + pm.collectionVariables.get( "TokenTail" );
Authentication = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse( Authentication ));

pm.request.headers.add("Authentication: basic " + Authentication );

如何访问头?API需要请求的TokenHead和TokenTail,令牌存储在本地存储中。

const TokenHead = localStorage.getItem('TokenHead');
const TokenTail = localStorage.getItem('TokenTail');
const Authentication = `${TokenHead}.${TokenTail}`;
const EncodedAuthentication = btoa(Authentication);

const headers = {
  'Content-Type': 'application/json',
  Authorization: `Basic ${EncodedAuthentication}`,
};

await axios
  .post(vURL, vData, headers)
  .then((vResponse) => {
    vStatus = vResponse.data.Status;
  });
sc4hvdpw

sc4hvdpw1#

这是解码标头

JSON.parse(Buffer.from(header, 'base64').toString())

示例
使用header输入数据解码

item = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
JSON.parse(Buffer.from(item, 'base64').toString())

解码输出

{ alg: 'HS256', typ: 'JWT' }

我认为您需要将用于身份验证的base64字符串从“.”替换为“:”。

const Authentication = `${TokenHead}.${TokenTail}`;

const Authentication = `${TokenHead}:${TokenTail}`;

此格式的示例在此处

There

How to decode a header的演示示例

Node.JS是跨平台兼容的,就像React一样,你完全可以在React框架中使用Node JS。

const CryptoJS = require("crypto-js")
const LocalStorage = require('node-localstorage').LocalStorage

const parseJwt = (item) => {
    return JSON.parse(Buffer.from(item, 'base64').toString())
}

// storage location
localStorage = new LocalStorage('./my-data')

// sample token
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
const tokenSplit = token.split(".")

// save token
localStorage.setItem('TokenHead', tokenSplit[0])
localStorage.setItem('TokenBody', tokenSplit[1])
localStorage.setItem('TokenTail', tokenSplit[2])

// load token
const TokenHead = localStorage.getItem('TokenHead')
const TokenBody = localStorage.getItem('TokenBody')
const TokenTail = localStorage.getItem('TokenTail')

const Authentication = TokenHead + '.' + TokenTail

// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
console.log(Authentication)

const EncodedAuthentication1 = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse( Authentication ));
// ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LlNmbEt4d1JKU01lS0tGMlFUNGZ3cE1lSmYzNlBPazZ5SlZfYWRRc3N3NWM=
console.log(EncodedAuthentication1)

const EncodedAuthentication2 = btoa(TokenHead + '.' + TokenTail);
// ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LlNmbEt4d1JKU01lS0tGMlFUNGZ3cE1lSmYzNlBPazZ5SlZfYWRRc3N3NWM=
console.log(EncodedAuthentication2)

const DecodeAuthentication2  = atob(EncodedAuthentication2)
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
console.log(DecodeAuthentication2)

const tokenBack = DecodeAuthentication2.split(".");

// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
console.log(tokenBack[0])

// { alg: 'HS256', typ: 'JWT' }
console.log(parseJwt(tokenBack[0]))

// { sub: '1234567890', name: 'John Doe', iat: 1516239022 }
console.log(parseJwt(TokenBody))

// SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
console.log(tokenBack[1])

安装依赖项

npm install crypto-js node-localstorage

结果

$ node test.js
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LlNmbEt4d1JKU01lS0tGMlFUNGZ3cE1lSmYzNlBPazZ5SlZfYWRRc3N3NWM=
ZXlKaGJHY2lPaUpJVXpJMU5pSXNJblI1Y0NJNklrcFhWQ0o5LlNmbEt4d1JKU01lS0tGMlFUNGZ3cE1lSmYzNlBPazZ5SlZfYWRRc3N3NWM=
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
{ alg: 'HS256', typ: 'JWT' }
{ sub: '1234567890', name: 'John Doe', iat: 1516239022 }
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

根据本测试,这两个函数的结果相同。

1使用CryptoJS

CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse( TokenHead + '.' + TokenTail))

第二个使用btoa

btoa(TokenHead + '.' + TokenTail)

解码使用atob

atob(EncodedAuthentication2)

使用localstorage进行电话后演示

这是使用localstorage获取Spotify令牌的真实的POST调用。
保存为get-token.js文件名。

const axios = require('axios')
const base64 = require('base-64')

const LocalStorage = require('node-localstorage').LocalStorage
localStorage = new LocalStorage('./my-data')

const storeToken = () => {
    localStorage.setItem('ClientId', '<your Spotify ClientId>')
    localStorage.setItem('ClientSecret', '<your Spotify Secret>')
}

const getToken = async () => {
    try {
        const URL='https://accounts.spotify.com/api/token'
        const client_id = localStorage.getItem('ClientId')
        const client_secret = localStorage.getItem('ClientSecret')
        const response = await axios.post(URL,
            new URLSearchParams({
                'grant_type': 'client_credentials'
            }),
            {
                headers:
                {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Authorization': 'Basic ' + base64.encode(client_id + ":" + client_secret)
                }
            })
        return Promise.resolve(response.data)
    } catch (err) {
        return Promise.reject(error)
    }
};

storeToken()

getToken()
    .then(data => {
        console.log(JSON.stringify(data, null, 4))
    })
    .catch(error => {
        console.log(error.message)
    })

安装依赖项

npm install axios base-64 node-localstorage

授权结果

相关问题