// OAuth 2.0 Client Credentials Flow Token Generator
import * as wmill from "windmill-client"
type oauth_credentials = {
nonce: string,
scope: string,
resource: string,
client_id: string,
token_url: string,
expires_in: string,
token_type: string,
access_token: string,
client_secret: string,
not_before_policy: string,
refresh_expires_in: string
}
/**
* Creates an OAuth 2.0 access token using the client credentials flow
* @param oauthResource - OAuth resource containing client_id and client_secret
* @param tokenUrl - The OAuth token endpoint URL (optional if provided in resource)
* @param scope - Optional scope for the token request
* @returns Object containing the access token and additional token information
*/
export async function main(
resourcepath:string ='',
variablepath:string = ''
) {
var oauthResource : oauth_credentials = await wmill.getResource(resourcepath);
// Prepare the request body for client credentials flow
const requestBody = new URLSearchParams({
grant_type: 'client_credentials',
client_id: oauthResource.client_id,
client_secret: oauthResource.client_secret
});
try {
// Make the token request
const response = await fetch(oauthResource.token_url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
},
body: requestBody.toString()
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Token request failed: ${response.status} ${response.statusText} - ${errorText}`);
}
const tokenData = await response.json();
oauthResource.expires_in = tokenData.expires_in;
oauthResource.token_type = tokenData.token_type;
oauthResource.refresh_expires_in = tokenData.refresh_expires_in;
oauthResource.not_before_policy = tokenData['not-before-policy'];
oauthResource.access_token = tokenData.access_token;
await wmill.setResource(oauthResource,resourcepath);
await wmill.setVariable(variablepath,oauthResource.access_token );
return {
token_type: tokenData.token_type,
expires_in: tokenData.expires_in,
message: 'Token updated successfully'
};
} catch (error) {
throw new Error(`Failed to create OAuth token: ${error.message}`);
}
}
Submitted by jansteinark898 232 days ago