我正在寻找一种创建 JWT 的方法,我可以使用 Postman Grant Type “授权代码”,使用现有的回调 URL(我无法修改 / localhost 是不允许的)。
我想创建一个 NodeJS / Go 小型应用程序,它可以模仿 Postman 授权此流程的方式。
AFAIK,唯一的方法是在由代码控制的窗口中运行重定向 url,并在登录后提取授权代码以获得正确的令牌。
登录页面后似乎无法提取此代码...
如果有人能指出我正确的方式:)
将添加一个我一直在玩的小 JS 代码(使用 puppeteer 来模仿 Postman 浏览器),自 以来就失败了"Invalid authorization code: 2j3ZN75HXNz4Uw4JsS3n8xhQpzVfa73Y"
,尽管这段代码绝对是正确的。
const puppeteer = require('puppeteer');
const url = "URL"
const ENV = {}
const account = {
username: "USERNAME", password: "PASSWORD"
}
// Sending a POST request with puppeteer, since I would like to do it from the browser instance itself, not axios.
async function gotoExtended(page, request) {
const { url, method, headers, postData } = request;
const cookies = await page.cookies()
console.log(cookies)
if (method !== 'GET' || postData || headers) {
let wasCalled = false;
await page.setRequestInterception(true);
const interceptRequestHandler = async (request) => {
try {
if (wasCalled) {
return await request.continue();
}
wasCalled = true;
const requestParams = {};
if (method !== 'GET') requestParams.method = method;
if (postData) requestParams.postData = postData;
if (headers) requestParams.headers = headers;
await request.continue(requestParams);
await page.setRequestInterception(false);
} catch (error) {
console.error('Error while request interception', { error });
}
};
await page.on('request', interceptRequestHandler);
}
return page.goto(url);
}
async function main() {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
let code;
page.on('response', response => {
const status = response.status()
if ((status >= 300) && (status <= 399)) {
console.log('Redirect from', response.url(), 'to', response.headers()['location'])
if (response.url().includes('callback?code=')) {
let str = response.url();
code = str.split('callback?code=')[1];
console.log(code)
}
}
})
await page.setViewport({width: 1200, height: 720});
await page.goto(url, {waitUntil: 'networkidle0'}); // wait until page load
await page.type('#j_username', account.username);
await page.type('#j_password', account.password);
// click and wait for navigation
await Promise.all([page.click('#logOnFormSubmit'), page.waitForNavigation({waitUntil: 'networkidle0'}),]);
const options = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "CORRECT - Base64 of ClientId:ClientSecret",
"Accept": "*/*",
"Cache-Control": "no-cache",
"Accept-Encoding": "gzip, deflate, br"
}
}
const data = `grant_type=authorization_code&code=${code}&redirect_uri=${ENV.redirectUri}&${ENV.clientId}`
await gotoExtended(page, { url: ENV.authURL, method: 'POST', postData: data, headers: options.headers });
console.log(await page.content());
await browser.close();
}
main().then(() => console.log("End"));
谢谢
编辑
代码确实有效,所以这就是我的想法。只是需要一些调整。