Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia
TypeScript apiapi-clientapi-restapi-testingdeveloper-toolsgraphqlhttphttp-clientpwarestrest-apispatestingtesting-toolstoolsvuevuejswebsocket
feat(common): add OAuth2 token type selector for `id_token` support (#6444)
Anwarul Islam8b6a0cbba8d0
diff --git a/packages/hoppscotch-common/src/composables/oauth2/useOAuth2GrantTypes.ts b/packages/hoppscotch-common/src/composables/oauth2/useOAuth2GrantTypes.tsindex dff495a22..598b0942d 100644--- a/packages/hoppscotch-common/src/composables/oauth2/useOAuth2GrantTypes.ts+++ b/packages/hoppscotch-common/src/composables/oauth2/useOAuth2GrantTypes.ts@@ -47,6 +47,18 @@ export const useOAuth2GrantTypes = (const t = useI18n()const toast = useToast()+ // Token type dropdown options (shared across all grant types). The OAuth2+ // dropdown component reads `ref.value.{id,label}` and assigns the whole+ // option object on click, so the ref must hold an `{id,label}` object — not+ // the raw string union.+ const tokenTypeOptions = [+ { id: "access_token" as const, label: "Access Token" },+ { id: "id_token" as const, label: "ID Token" },+ ]++ const tokenTypeOptionFor = (value: string | undefined) =>+ tokenTypeOptions.find((o) => o.id === value) ?? tokenTypeOptions[0]+// Helper function to prepare request parametersconst prepareRequestParams = (params: Ref<AuthRequestParam[] | TokenRequestParam[]>@@ -210,6 +222,20 @@ export const useOAuth2GrantTypes = (})+ const tokenType = refWithCallbackOnChange(+ tokenTypeOptionFor(auth.value.grantTypeInfo.tokenType),+ (value) => {+ if (!("tokenType" in auth.value.grantTypeInfo)) {+ return+ }++ auth.value.grantTypeInfo = {+ ...auth.value.grantTypeInfo,+ tokenType: value.id,+ }+ }+ )+const refreshToken = async () => {const grantTypeInfo = auth.value.grantTypeInfo@@ -269,6 +295,7 @@ export const useOAuth2GrantTypes = (authRequestParams: preparedAuthRequestParams.value,tokenRequestParams: preparedTokenRequestParams.value,refreshRequestParams: preparedRefreshRequestParams.value,+ tokenType: tokenType.value.id,}const unwrappedParams = replaceTemplateStringsInObjectValues(params)@@ -358,6 +385,15 @@ export const useOAuth2GrantTypes = (type: "text" as const,ref: scopes,},+ {+ id: "tokenType",+ label: "Token Type",+ type: "dropdown" as const,+ ref: tokenType,+ tippyRefName: "tokenTypeTippyActions",+ tippyRef: { value: null },+ options: tokenTypeOptions,+ },]})@@ -449,6 +485,20 @@ export const useOAuth2GrantTypes = (})+ const tokenType = refWithCallbackOnChange(+ tokenTypeOptionFor(auth.value.grantTypeInfo.tokenType),+ (value) => {+ if (!("tokenType" in auth.value.grantTypeInfo)) {+ return+ }++ auth.value.grantTypeInfo = {+ ...auth.value.grantTypeInfo,+ tokenType: value.id,+ }+ }+ )+const runAction = async () => {const values: ClientCredentialsFlowParams =replaceTemplateStringsInObjectValues({@@ -459,6 +509,7 @@ export const useOAuth2GrantTypes = (clientAuthentication: clientAuthentication.value.id,tokenRequestParams: preparedTokenRequestParams.value,refreshRequestParams: preparedRefreshRequestParams.value,+ tokenType: tokenType.value.id,})const parsedArgs = clientCredentials.params.safeParse(values)@@ -524,6 +575,15 @@ export const useOAuth2GrantTypes = (},],},+ {+ id: "tokenType",+ label: "Token Type",+ type: "dropdown" as const,+ ref: tokenType,+ tippyRefName: "tokenTypeTippyActions",+ tippyRef: { value: null },+ options: tokenTypeOptions,+ },]})@@ -612,6 +672,20 @@ export const useOAuth2GrantTypes = (})+ const tokenType = refWithCallbackOnChange(+ tokenTypeOptionFor(auth.value.grantTypeInfo.tokenType),+ (value) => {+ if (!("tokenType" in auth.value.grantTypeInfo)) {+ return+ }++ auth.value.grantTypeInfo = {+ ...auth.value.grantTypeInfo,+ tokenType: value.id,+ }+ }+ )+const runAction = async () => {const values: PasswordFlowParams =replaceTemplateStringsInObjectValues({@@ -623,6 +697,7 @@ export const useOAuth2GrantTypes = (password: password.value,tokenRequestParams: preparedTokenRequestParams.value,refreshRequestParams: preparedRefreshRequestParams.value,+ tokenType: tokenType.value.id,})const parsedArgs = passwordFlow.params.safeParse(values)@@ -682,6 +757,15 @@ export const useOAuth2GrantTypes = (type: "text" as const,ref: scopes,},+ {+ id: "tokenType",+ label: "Token Type",+ type: "dropdown" as const,+ ref: tokenType,+ tippyRefName: "tokenTypeTippyActions",+ tippyRef: { value: null },+ options: tokenTypeOptions,+ },]})@@ -727,6 +811,20 @@ export const useOAuth2GrantTypes = (})+ const tokenType = refWithCallbackOnChange(+ tokenTypeOptionFor(auth.value.grantTypeInfo.tokenType),+ (value) => {+ if (!("tokenType" in auth.value.grantTypeInfo)) {+ return+ }++ auth.value.grantTypeInfo = {+ ...auth.value.grantTypeInfo,+ tokenType: value.id,+ }+ }+ )+const runAction = () => {const values: ImplicitOauthFlowParams =replaceTemplateStringsInObjectValues({@@ -735,6 +833,7 @@ export const useOAuth2GrantTypes = (scopes: scopes.value,authRequestParams: preparedAuthRequestParams.value,refreshRequestParams: preparedRefreshRequestParams.value,+ tokenType: tokenType.value.id,})const unwrappedValues = replaceTemplateStringsInObjectValues(values)@@ -770,6 +869,15 @@ export const useOAuth2GrantTypes = (type: "text" as const,ref: scopes,},+ {+ id: "tokenType",+ label: "Token Type",+ type: "dropdown" as const,+ ref: tokenType,+ tippyRefName: "tokenTypeTippyActions",+ tippyRef: { value: null },+ options: tokenTypeOptions,+ },]})diff --git a/packages/hoppscotch-common/src/services/oauth/flows/authCode.ts b/packages/hoppscotch-common/src/services/oauth/flows/authCode.tsindex aff25d2fa..e674a7d27 100644--- a/packages/hoppscotch-common/src/services/oauth/flows/authCode.ts+++ b/packages/hoppscotch-common/src/services/oauth/flows/authCode.ts@@ -30,6 +30,7 @@ const AuthCodeOauthFlowParamsSchema = AuthCodeGrantTypeParams.omit({authRequestParams: z.array(OAuth2AuthRequestParam),tokenRequestParams: z.array(OAuth2ParamSchema),refreshRequestParams: z.array(OAuth2ParamSchema),+ tokenType: z.enum(["access_token", "id_token"]).optional(),}).refine((params) => {@@ -72,6 +73,7 @@ export const getDefaultAuthCodeOauthFlowParams =authRequestParams: [],refreshRequestParams: [],tokenRequestParams: [],+ tokenType: "access_token",})const initAuthCodeOauthFlow = async ({@@ -85,6 +87,7 @@ const initAuthCodeOauthFlow = async ({authRequestParams,refreshRequestParams,tokenRequestParams,+ tokenType,}: AuthCodeOauthFlowParams) => {const state = generateRandomString()@@ -137,6 +140,7 @@ const initAuthCodeOauthFlow = async ({active: booleansendIn?: string}>+ tokenType?: "access_token" | "id_token"} = {state,grant_type: "AUTHORIZATION_CODE",@@ -151,6 +155,7 @@ const initAuthCodeOauthFlow = async ({authRequestParams,refreshRequestParams,tokenRequestParams,+ tokenType,}if (codeVerifier && codeChallenge) {@@ -239,6 +244,7 @@ const handleRedirectForAuthCodeOauthFlow = async (localConfig: string) => {clientID: z.string(),codeVerifier: z.string().optional(),codeChallenge: z.string().optional(),+ tokenType: z.enum(["access_token", "id_token"]).optional(),})const decodedLocalConfig = expectedSchema.safeParse(@@ -306,11 +312,19 @@ const handleRedirectForAuthCodeOauthFlow = async (localConfig: string) => {return E.left("AUTH_TOKEN_REQUEST_INVALID_RESPONSE" as const)}+ // Get the token type preference from the persisted config+ const tokenTypePreference =+ decodedLocalConfig.data.tokenType || "access_token"+return E.right({access_token:- parsedTokenResponse.data.access_token ||- parsedTokenResponse.data.id_token ||- "",+ tokenTypePreference === "id_token"+ ? parsedTokenResponse.data.id_token ||+ parsedTokenResponse.data.access_token ||+ ""+ : parsedTokenResponse.data.access_token ||+ parsedTokenResponse.data.id_token ||+ "",refresh_token: parsedTokenResponse.data.refresh_token,})}diff --git a/packages/hoppscotch-common/src/services/oauth/flows/clientCredentials.ts b/packages/hoppscotch-common/src/services/oauth/flows/clientCredentials.tsindex 57604e0d2..5001681e6 100644--- a/packages/hoppscotch-common/src/services/oauth/flows/clientCredentials.ts+++ b/packages/hoppscotch-common/src/services/oauth/flows/clientCredentials.ts@@ -28,6 +28,7 @@ const ClientCredentialsFlowParamsSchema = ClientCredentialsGrantTypeParams.omit(// Override optional arrays to be required for the service layertokenRequestParams: z.array(OAuth2ParamSchema),refreshRequestParams: z.array(OAuth2ParamSchema),+ tokenType: z.enum(["access_token", "id_token"]).optional(),}).refine((params) => {@@ -55,6 +56,7 @@ export const getDefaultClientCredentialsFlowParams =clientAuthentication: "IN_BODY",tokenRequestParams: [],refreshRequestParams: [],+ tokenType: "access_token",})const initClientCredentialsOAuthFlow = async (@@ -79,9 +81,14 @@ const initClientCredentialsOAuthFlow = async (if (E.isLeft(jsonResponse)) return E.left("AUTH_TOKEN_REQUEST_FAILED")- const withAccessTokenSchema = z.object({- access_token: z.string(),- })+ const withAccessTokenSchema = z+ .object({+ access_token: z.string().optional(),+ id_token: z.string().optional(),+ })+ .refine((data) => data.access_token || data.id_token, {+ message: "Either access_token or id_token must be present",+ })const parsedTokenResponse = withAccessTokenSchema.safeParse(jsonResponse.right@@ -91,9 +98,21 @@ const initClientCredentialsOAuthFlow = async (toast.error("AUTH_TOKEN_REQUEST_INVALID_RESPONSE")}- return parsedTokenResponse.success- ? E.right(parsedTokenResponse.data)- : E.left("AUTH_TOKEN_REQUEST_INVALID_RESPONSE" as const)+ if (parsedTokenResponse.success) {+ // Return the preferred token type+ const token =+ payload.tokenType === "id_token"+ ? parsedTokenResponse.data.id_token ||+ parsedTokenResponse.data.access_token+ : parsedTokenResponse.data.access_token ||+ parsedTokenResponse.data.id_token++ if (token) {+ return E.right({ access_token: token })+ }+ }++ return E.left("AUTH_TOKEN_REQUEST_INVALID_RESPONSE" as const)}const handleRedirectForAuthCodeOauthFlow = async (localConfig: string) => {diff --git a/packages/hoppscotch-common/src/services/oauth/flows/implicit.ts b/packages/hoppscotch-common/src/services/oauth/flows/implicit.tsindex 6d587ea7b..589a9964a 100644--- a/packages/hoppscotch-common/src/services/oauth/flows/implicit.ts+++ b/packages/hoppscotch-common/src/services/oauth/flows/implicit.ts@@ -25,6 +25,7 @@ const ImplicitOauthFlowParamsSchema = ImplicitOauthFlowParamsData.omit({// Override optional arrays to be required for the service layerauthRequestParams: z.array(OAuth2AuthRequestParam),refreshRequestParams: z.array(OAuth2ParamSchema),+ tokenType: z.enum(["access_token", "id_token"]).optional(),}).refine((params) => {return (@@ -45,6 +46,7 @@ export const getDefaultImplicitOauthFlowParams =scopes: undefined,authRequestParams: [],refreshRequestParams: [],+ tokenType: "access_token",})const initImplicitOauthFlow = async ({@@ -52,6 +54,7 @@ const initImplicitOauthFlow = async ({scopes,authEndpoint,authRequestParams,+ tokenType,}: ImplicitOauthFlowParams) => {const state = generateRandomString()@@ -73,6 +76,7 @@ const initImplicitOauthFlow = async ({scopes,state,authRequestParams,+ tokenType,},grant_type: "IMPLICIT",})@@ -115,6 +119,7 @@ const handleRedirectForAuthCodeOauthFlow = async (localConfig: string) => {const accessToken =params.get("access_token") || paramsFromHash.get("access_token")+ const idToken = params.get("id_token") || paramsFromHash.get("id_token")const state = params.get("state") || paramsFromHash.get("state")const error = params.get("error") || paramsFromHash.get("error")@@ -122,14 +127,11 @@ const handleRedirectForAuthCodeOauthFlow = async (localConfig: string) => {return E.left("AUTH_SERVER_RETURNED_ERROR")}- if (!accessToken) {- return E.left("AUTH_TOKEN_REQUEST_FAILED")- }-const expectedSchema = z.object({source: z.optional(z.string()),state: z.string(),clientID: z.string(),+ tokenType: z.enum(["access_token", "id_token"]).optional(),})const decodedLocalConfig = expectedSchema.safeParse(@@ -145,8 +147,22 @@ const handleRedirectForAuthCodeOauthFlow = async (localConfig: string) => {return E.left("INVALID_STATE")}+ // Get the token type preference from the persisted config+ const tokenTypePreference =+ decodedLocalConfig.data.tokenType || "access_token"++ // Return the preferred token type+ const token =+ tokenTypePreference === "id_token"+ ? idToken || accessToken+ : accessToken || idToken++ if (!token) {+ return E.left("AUTH_TOKEN_REQUEST_FAILED")+ }+return E.right({- access_token: accessToken,+ access_token: token,})}diff --git a/packages/hoppscotch-common/src/services/oauth/flows/password.ts b/packages/hoppscotch-common/src/services/oauth/flows/password.tsindex f48e47486..b55cccebe 100644--- a/packages/hoppscotch-common/src/services/oauth/flows/password.ts+++ b/packages/hoppscotch-common/src/services/oauth/flows/password.ts@@ -25,6 +25,7 @@ const PasswordFlowParamsSchema = PasswordGrantTypeParams.omit({// Override optional arrays to be required for the service layertokenRequestParams: z.array(OAuth2ParamSchema),refreshRequestParams: z.array(OAuth2ParamSchema),+ tokenType: z.enum(["access_token", "id_token"]).optional(),}).refine((params) => {@@ -52,6 +53,7 @@ export const getDefaultPasswordFlowParams = (): PasswordFlowParams => ({password: "",tokenRequestParams: [],refreshRequestParams: [],+ tokenType: "access_token",})const initPasswordOauthFlow = async ({@@ -62,6 +64,7 @@ const initPasswordOauthFlow = async ({scopes,authEndpoint,tokenRequestParams,+ tokenType,}: PasswordFlowParams) => {const toast = useToast()@@ -122,21 +125,38 @@ const initPasswordOauthFlow = async ({return E.left("AUTH_TOKEN_REQUEST_FAILED" as const)}- const withAccessTokenSchema = z.object({- access_token: z.string(),- })+ const withAccessTokenSchema = z+ .object({+ access_token: z.string().optional(),+ id_token: z.string().optional(),+ })+ .refine((data) => data.access_token || data.id_token, {+ message: "Either access_token or id_token must be present",+ })- const responsePayload = parseBytesToJSON<{ access_token: string }>(- res.right.body.body- )+ const responsePayload = parseBytesToJSON<{+ access_token?: string+ id_token?: string+ }>(res.right.body.body)if (O.isSome(responsePayload)) {const parsedTokenResponse = withAccessTokenSchema.safeParse(responsePayload.value)- return parsedTokenResponse.success- ? E.right(parsedTokenResponse.data)- : E.left("AUTH_TOKEN_REQUEST_INVALID_RESPONSE" as const)++ if (parsedTokenResponse.success) {+ // Return the preferred token type+ const token =+ tokenType === "id_token"+ ? parsedTokenResponse.data.id_token ||+ parsedTokenResponse.data.access_token+ : parsedTokenResponse.data.access_token ||+ parsedTokenResponse.data.id_token++ if (token) {+ return E.right({ access_token: token })+ }+ }}return E.left("AUTH_TOKEN_REQUEST_INVALID_RESPONSE" as const)diff --git a/packages/hoppscotch-data/src/rest/v/15/auth.ts b/packages/hoppscotch-data/src/rest/v/15/auth.tsindex e3df82b69..08b8c0e52 100644--- a/packages/hoppscotch-data/src/rest/v/15/auth.ts+++ b/packages/hoppscotch-data/src/rest/v/15/auth.ts@@ -37,22 +37,26 @@ export const AuthCodeGrantTypeParams = AuthCodeGrantTypeParamsOld.extend({authRequestParams: z.array(OAuth2AuthRequestParam).optional().default([]),tokenRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),refreshRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),+ tokenType: z.enum(["access_token", "id_token"]).optional().catch("access_token"),})export const ClientCredentialsGrantTypeParams =ClientCredentialsGrantTypeParamsOld.extend({tokenRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),refreshRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),+ tokenType: z.enum(["access_token", "id_token"]).optional().catch("access_token"),})export const PasswordGrantTypeParams = PasswordGrantTypeParamsOld.extend({tokenRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),refreshRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),+ tokenType: z.enum(["access_token", "id_token"]).optional().catch("access_token"),})export const ImplicitOauthFlowParams = ImplicitOauthFlowParamsOld.extend({authRequestParams: z.array(OAuth2AuthRequestParam).optional().default([]),refreshRequestParams: z.array(OAuth2AdvancedParam).optional().default([]),+ tokenType: z.enum(["access_token", "id_token"]).optional().catch("access_token"),})// Extend OAuth2 with advanced parameters