Skip to content

Instantly share code, notes, and snippets.

@pmicko
Last active February 22, 2024 14:02
Show Gist options
  • Save pmicko/41fa2407f72ca4ac5d6f2e315571879c to your computer and use it in GitHub Desktop.
Save pmicko/41fa2407f72ca4ac5d6f2e315571879c to your computer and use it in GitHub Desktop.
Cypress 10+ & Identity Server 4 - Programmatic login using API (authorization code flow + PKCE) & UI login
import { LOGIN_SELECTORS as selectors} from "./login.selectors"
import { authenticationData as authData } from "../../fixtures/authData"
const identityServerUrl = Cypress.env("IDENTITY_SERVER_URL")
Cypress.Commands.add('loginAPI', (username, password) => {
const authEndpoint = `${identityServerUrl}/connect/authorize`
const loginPageEndpoint = `${identityServerUrl}/Account/Login`
cy.session(['loginAPI', username], () => {
cy.request({
url: authEndpoint,
followRedirect: true,
qs: {
response_type: 'code',
client_id: authData.client_id,
redirect_uri: `${Cypress.config('baseUrl')}/callback`,
scope: authData.scope,
nonce: authData.nonce,
state: authData.state,
code_challenge: authData.code_challenge,
code_challenge_method: authData.code_challenge_method,
}
}).its('body').then((body) => {
const $html = Cypress.$(body)
const token = $html.find("input[name=__RequestVerificationToken]").val()
const returnUrl = $html.find('#ReturnUrl').val()
cy.request({
method: "POST",
failOnStatusCode: false,
url: loginPageEndpoint,
form: true,
body: {
returnUrl,
username,
password,
__RequestVerificationToken: token,
button: 'login',
RememberLogin: false
}
}).then((resp) => {
expect(resp.status).to.eq(200)
})
})
cy.visit('/')
})
})
Cypress.Commands.add('loginUI', (username, password) => {
cy.session(['loginUI', username], () => {
cy.visit('/')
cy.origin(identityServerUrl,
{args: {selectors, username, password}},
({selectors, username, password}) => {
cy.get(selectors.inputUsername).type(username)
cy.get(selectors.inputPassword).type(password)
cy.get(selectors.buttonLogin).click()
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment