Simple OAuth Token Handling with Cypress
Here’s a quick (and dirty?) way to handle requesting an access token and using it in a subsequent request.
You should probably pull the client_secret from an environment variable (not shown below).
commands.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/** * Get an oAuth access token. */ Cypress.Commands.add('getOauthAccessToken', () => { cy.request({ method: 'POST', url: '/oauth/token', form: true, body: { grant_type: 'client_credentials', client_id: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx', client_secret: 'xxxxxxxxxxxxxxxxxxxx', scope: '', }, }); }); |
some-tests.spec.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
describe('API Foobar', function() { it('Gets expected values from GET /oauth/debug', function() { cy.getOauthAccessToken().then(oAuthResp => { cy.request({ method: 'GET', url: '/oauth/debug?_format=json', headers: { 'Authorization': `Bearer ${oAuthResp.body.access_token}`, }, }).should((resp) => { expect(resp.status).to.eq(200); expect(resp.body.roles).to.deep.contain('authenticated'); expect(resp.body.roles).to.deep.contain('api_foobar'); }); }); }); }); |