diff --git a/packages/client/src/grant-token.test.ts b/packages/client/src/grant-token.test.ts index d6594141b..a7301c0df 100644 --- a/packages/client/src/grant-token.test.ts +++ b/packages/client/src/grant-token.test.ts @@ -1,6 +1,6 @@ import nock from 'nock'; -import { grantTokenByAuthorizationCode } from './grant-token'; +import { grantTokenByAuthorizationCode, grantTokenByRefreshToken } from './grant-token'; describe('grantTokenByAuthorizationCode', () => { test('get tokenSet paramaters', async () => { @@ -46,3 +46,26 @@ describe('grantTokenByAuthorizationCode', () => { ).rejects.toThrowError(); }); }); + +describe('grantTokenByRefreshToken', () => { + test('get tokenSet paramaters', async () => { + const successResponse = { + access_token: 'access_token', + expires_in: 3600, + id_token: 'id_token', + refresh_token: 'refresh_token', + }; + + nock('https://logto.dev', { allowUnmocked: true }) + .post('/oidc/token') + .reply(200, successResponse); + + const tokenSet = await grantTokenByRefreshToken( + 'https://logto.dev/oidc/token', + 'client_id', + 'refresh_token' + ); + + expect(tokenSet).toMatchObject(successResponse); + }); +}); diff --git a/packages/client/src/grant-token.ts b/packages/client/src/grant-token.ts index db8d893f3..f70e08a35 100644 --- a/packages/client/src/grant-token.ts +++ b/packages/client/src/grant-token.ts @@ -38,3 +38,27 @@ export const grantTokenByAuthorizationCode = async ( return result.data; }; + +export const grantTokenByRefreshToken = async ( + endpoint: string, + clientId: string, + refreshToken: string +): Promise => { + const parameters = new URLSearchParams(); + parameters.append('grant_type', 'refresh_token'); + parameters.append('client_id', clientId); + parameters.append('refresh_token', refreshToken); + + const response = await opRequest.post(endpoint, parameters, { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + }); + const result = TokenSetParametersSchema.safeParse(response.data); + + if (!result.success) { + throw new OPError({ originalError: result.error }); + } + + return result.data; +};