-
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
12345678910111213141516/*** 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
12345678910111213141516171819describe('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');});});});});