You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

110 lines
2.7 KiB

// installable packages
const base64url = require("base64url");
const { v4: uuidv4 } = require("uuid");
const fetch = require("node-fetch").default;
// native packages
const crypto = require("crypto");
const { URL, URLSearchParams } = require("url");
// config
const BASE_URL = "http://localhost:8080";
const REALM = "demorealm";
const REDIRECT_URI = "com.juice.booster3://auth";
const CLIENT_ID = "native-webview";
const sha256encrypt = (code) => {
const base64Digest = crypto
.createHash("sha256")
.update(code)
.digest("base64");
return base64url.fromBase64(base64Digest);
};
const nonceFactory = () => {
const timestamp = Date.now();
return sha256encrypt(timestamp.toString());
};
function generateAuthUrl() {
const nonce = uuidv4();
const state = uuidv4();
const url = new URL(
`${BASE_URL}/auth/realms/${REALM}/protocol/openid-connect/auth`,
);
url.searchParams.append("client_id", CLIENT_ID);
url.searchParams.append("redirect_uri", REDIRECT_URI);
url.searchParams.append("state", state);
url.searchParams.append("response_mode", "fragment");
url.searchParams.append("response_type", "code");
url.searchParams.append("scope", "openid");
url.searchParams.append("nonce", nonce);
console.log(url.href);
}
async function getTokenByUrl(urlString) {
let url = new URL(urlString);
let code = new URLSearchParams(url.hash).get("code");
console.log(`Auth with code is: ${code}`);
url = new URL(
`${BASE_URL}/auth/realms/${REALM}/protocol/openid-connect/token`,
);
const payload = {
client_id: CLIENT_ID,
code,
grant_type: "authorization_code",
redirect_uri: REDIRECT_URI,
};
let response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "*/*",
},
redirect: "manual",
body: new URLSearchParams(payload).toString(),
});
const token = await response.json();
console.log(token);
}
async function refresh(refresh_token) {
const url = new URL(
`${BASE_URL}/auth/realms/${REALM}/protocol/openid-connect/token`,
);
const payload = {
client_id: CLIENT_ID,
refresh_token,
grant_type: "refresh_token",
redirect_uri: REDIRECT_URI,
};
let response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "*/*",
},
redirect: "manual",
body: new URLSearchParams(payload).toString(),
});
const token = await response.json();
console.log(token);
}
if (require.main === module) {
const redirectUri = process.argv[2];
if (redirectUri == null) {
generateAuthUrl();
} else {
getTokenByUrl(redirectUri);
}
}