6

目标是以access token编程方式从 MSAL 获取赛普拉斯 e2e 测试。我们使用 V2.0 API。

根据这个我首先需要得到authorization codehttps://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-authorization-code

获取access token https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow#request-an-access-token

所以为了得到authorization code我需要做这个请求

// GET
// Line breaks for legibility only

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
&response_mode=query
&scope=openid%20offline_access%20https%3A%2F%2Fgraph.microsoft.com%2Fmail.read
&state=12345
&code_challenge=YTFjNjI1OWYzMzA3MTI4ZDY2Njg5M2RkNmVjNDE5YmEyZGRhOGYyM2IzNjdmZWFhMTQ1ODg3NDcxY2Nl
&code_challenge_method=S256

但这会返回text/html,所以我需要手动登录才能获取代码。

有没有办法以编程方式获得authorization code

4

1 回答 1

7

这就是我通过创建login命令解决它的方法。该命令以编程方式获取令牌并将其存储到 localStorage。

import 'cypress-localstorage-commands';

Cypress.Commands.add('login', () => {
  const request = {
    method: 'POST',
    form: true,
    url: `https://login.microsoftonline.com/${Cypress.config('tenantId')}/oauth2/v2.0/token`,
    body: {
      grant_type: 'client_credentials',
      client_id: Cypress.config('clientId'),
      client_secret: Cypress.config('clientSecret'),
      scope: `${Cypress.config('clientId')}/.default`,
    },
  };

  cy.request(request).then(response => cy.setLocalStorage('msal.idtoken', response.body.access_token));
});
于 2021-07-06T05:27:33.393 回答