| 25 | |
| 26 | export class OidcModel { |
| 27 | static async getSignInUrl( |
| 28 | { |
| 29 | requestPermissions, |
| 30 | extraState = {}, |
| 31 | }: { |
| 32 | requestPermissions: string[]; |
| 33 | extraState?: OidcExtraState; |
| 34 | }, |
| 35 | ): Promise<string> { |
| 36 | const state = { |
| 37 | ...extraState, |
| 38 | random: generateRandomCode(8), |
| 39 | }; |
| 40 | |
| 41 | const config = await AppConfig.getConfig(); |
| 42 | |
| 43 | const baseUrl = config.auth.baseUrl; |
| 44 | const oidcBaseUrl = config.auth.singleSignOnUrl; |
| 45 | const oidcOptions = oidcBaseUrl.startsWith('http://') |
| 46 | ? { execute: [openIdClient.allowInsecureRequests] } |
| 47 | : undefined; |
| 48 | |
| 49 | try { |
| 50 | const oidcConfig = await openIdClient.discovery( |
| 51 | new URL(oidcBaseUrl), |
| 52 | OIDC_CLIENT_ID, |
| 53 | OIDC_CLIENT_SECRET, |
| 54 | undefined, |
| 55 | oidcOptions, |
| 56 | ); |
| 57 | |
| 58 | const redirectUrl = `${baseUrl}${redirectUrlPath}`; |
| 59 | |
| 60 | const codeVerifier = openIdClient.randomPKCECodeVerifier(); |
| 61 | |
| 62 | const params = { |
| 63 | client_id: OIDC_CLIENT_ID, |
| 64 | redirect_uri: redirectUrl, |
| 65 | state: btoa(JSON.stringify(state)), |
| 66 | scope: requestPermissions.join(' '), |
| 67 | code_challenge: await openIdClient.calculatePKCECodeChallenge(codeVerifier), |
| 68 | code_challenge_method: 'S256', |
| 69 | }; |
| 70 | |
| 71 | const oidcStateCache = new SimpleCache(`oidc:state:${params.state}`); |
| 72 | |
| 73 | await oidcStateCache.set(JSON.stringify({ state, codeVerifier })); |
| 74 | |
| 75 | const oidcUrl = openIdClient.buildAuthorizationUrl(oidcConfig, params); |
| 76 | |
| 77 | return oidcUrl.href; |
| 78 | } catch (error) { |
| 79 | console.log(`Failed to get OIDC sign in URL: ${error}`); |
| 80 | console.error(error); |
| 81 | |
| 82 | return ''; |
| 83 | } |
| 84 | } |