Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NilukaSripalim/51d4d14de79cbc190273783b4280230f to your computer and use it in GitHub Desktop.
Save NilukaSripalim/51d4d14de79cbc190273783b4280230f to your computer and use it in GitHub Desktop.
This Cypress test script logs in to the WSO2 Identity Server console, creates a SCIM user, and creates an OIDC application. After each test, it deletes the created user and application to clean up the environment. The createScimUser, createApplication, deleteUser, and filterAndDeleteApplication functions handle the user and application creation …
/*
* Copyright (c) 2024 WSO2 LLC. (http://www.wso2.org)
* All rights reserved.
*
* This software is the property of WSO2 LLC. and its suppliers, if any.
* Dissemination of any information or reproduction of any material contained
* herein in any form is strictly forbidden, unless permitted by WSO2 expressly.
* You may not alter or remove any copyright or other notice from copies of this content.
*/
import { EnvironmentConfig } from "../../configs";
// Define the parameters
const baseUrl = "https://localhost:9445";
const consoleEndPoint = "/console";
const scimUserEndPoint = "/scim2/Users";
const applicationEndPoint = "/api/server/v1/applications";
const authorizedUser = { userName: "admin", password: "<AdminUserPassword>" };
const shouldSkipConsoleLanding = false; // Set it to true if needed
const cacheSession = true; // Set it to false if needed
// User & application creation.
const applicationName = "oidc-application";
const userName = "kim";
const filtrUserName = "userName eq " + userName;
const filterApplicationName = "name eq " + applicationName;
const password = "";
const userAttributes = {
"name": {
"givenName": "Kim",
"familyName": "Berry"
},
"emails": [
{
"type": "home",
"value": "kim@gmail.com",
"primary": true
},
{
"type": "work",
"value": "kim@wso2.com"
}
]
};
describe("WSO2 Identity Server Console Login with User and Application Management", () => {
it("should login to the WSO2 Identity Server console", () => {
// Call the consoleLogin function
consoleLogin(baseUrl + consoleEndPoint, authorizedUser, shouldSkipConsoleLanding, cacheSession);
// Basic Data Creation.
createScimUser(userName, password, userAttributes);
createApplication(oidcApplicationPayload);
});
after(() => {
// Delete created User via SCIM API.
deleteUser(filtrUserName);
// Delete created Application.
filterAndDeleteApplication(filterApplicationName);
});
});
const consoleLogin = (
url: string,
authorizedUser: { userName: string; password: string },
shouldSkipConsoleLanding: boolean,
cacheSession: boolean
): void => {
const login = () => {
cy.visit(url);
cy.get("#usernameUserInput").type(authorizedUser.userName);
cy.get("#password").type(authorizedUser.password);
cy.get("#sign-in-button").click();
if (shouldSkipConsoleLanding) {
// If shouldSkipConsoleLanding is set to true, then perform additional actions here
}
if (EnvironmentConfig.skipTestInLocalEnv()) cy.clearCookies();
cy.declineMarketingConsent();
};
if (cacheSession) {
cy.session(authorizedUser.userName, login);
} else {
login();
}
};
const createScimUser = (userName: string, password: string, userAttributes: any): void => {
// Base64 encoding of username:password
const authHeader = `Basic ${btoa(`${authorizedUser.userName}:${authorizedUser.password}`)}`;
cy.log(authHeader)
const headers = {
"Accept": "application/scim+json",
"Content-Type": "application/scim+json",
"Authorization": authHeader
};
const userData = {
"schemas": [],
"userName": userName,
"password": password,
...userAttributes
};
cy.request({
method: "POST",
url: baseUrl + scimUserEndPoint,
headers: headers,
body: JSON.stringify(userData)
});
};
// Application Creation (SP OIDC).
/**
* The function `createApplication` sends a POST request with authentication headers and application
* data to a specified endpoint.
* @param {any} applicationData - The `applicationData` parameter in the `createApplication` function.
*/
const createApplication = (applicationData: any): void => {
// Base64 encoding of username:password
const authHeader = `Basic ${btoa(`${authorizedUser.userName}:${authorizedUser.password}`)}`;
const headers = {
"accept": "*/*",
"Authorization": authHeader,
"Content-Type": "application/json"
};
cy.request({
method: "POST",
url: baseUrl + applicationEndPoint,
headers: headers,
body: JSON.stringify(applicationData)
});
};
const oidcApplicationPayload = {
"name": applicationName,
"advancedConfigurations": {
"discoverableByEndUsers": false,
"skipLogoutConsent": true,
"skipLoginConsent": true
},
"authenticationSequence": {
"type": "DEFAULT",
"steps": [
{
"id": 1,
"options": [
{
"idp": "LOCAL",
"authenticator": "basic"
}
]
}
]
},
"claimConfiguration": {
"dialect": "LOCAL",
"requestedClaims": [
{
"claim": {
"uri": "http://wso2.org/claims/username"
}
}
]
},
"inboundProtocolConfiguration": {
"oidc": {
"grantTypes": ["authorization_code"],
"allowedOrigins": ["https://example.com"],
"callbackURLs": ["https://example.com/login"],
"publicClient": false,
"refreshToken": {
"expiryInSeconds": 86400
}
}
},
"templateId": "b9c5e11e-fc78-484b-9bec-015d247561b8",
"associatedRoles": {
"allowedAudience": "APPLICATION",
"roles": []
}
};
/**
* The function `deleteUser` deletes a user by username after retrieving the user ID and then deleting
* the user by ID using Cypress requests.
* @param filter - The `filter` parameter in the `deleteUser` function is used to specify the criteria.
*/
const deleteUser = (filter) => {
// Get user ID by username
const getUserIdByUsername = (filter: string) => {
const authHeader = `Basic ${btoa(`${authorizedUser.userName}:${authorizedUser.password}`)}`;
return cy.request({
method: "GET",
url: `${baseUrl + scimUserEndPoint}?filter=${encodeURIComponent(filter)}`,
headers: {
Authorization: authHeader,
Accept: "application/scim+json",
},
}).then((response) => {
// Extract userId from the response
const userId: string = response.body?.Resources?.[0]?.id;
return userId;
});
};
// Delete user by ID
const deleteUserById = (userId: string) => {
const authHeader = `Basic ${btoa(`${authorizedUser.userName}:${authorizedUser.password}`)}`;
return cy.request({
method: "DELETE",
url: `${baseUrl + scimUserEndPoint}/${userId}`,
headers: {
Authorization: authHeader,
Accept: "application/scim+json",
},
}).then((response) => {
// Handle response, e.g., validate status code, body, etc.
return response;
});
};
// Call getUserIdByUsername to get the userId
return getUserIdByUsername(filter)
.then((userId) => {
// If userId is available, delete the user
if (userId) {
return deleteUserById(userId);
} else {
// Handle the case where userId is not available
// (e.g., user not found)
cy.log("User not found.");
return null;
}
});
};
/**
* The function `filterAndDeleteApplication` filters applications by name, retrieves the application
* ID, and deletes the application if found.
* @param appNameFilter - The `appNameFilter` parameter is used to filter applications by name.
*/
const filterAndDeleteApplication = (appNameFilter) => {
// Function to filter applications by name and get the application ID
const getApplicationIdByName = (appName) => {
const authHeader = `Basic ${btoa(`${authorizedUser.userName}:${authorizedUser.password}`)}`;
return cy.request({
method: "GET",
url: `${baseUrl + applicationEndPoint}?filter=${encodeURIComponent(appNameFilter)}`,
headers: {
Authorization: authHeader,
Accept: "application/json",
},
}).then((response) => {
// Extract application ID from the response
const applicationId = response.body?.applications?.[0]?.id;
return applicationId;
});
};
// Function to delete application by ID
const deleteApplicationById = (applicationId) => {
const authHeader = `Basic ${btoa(`${authorizedUser.userName}:${authorizedUser.password}`)}`;
return cy.request({
method: "DELETE",
url: `${baseUrl + applicationEndPoint}/${applicationId}`,
headers: {
Authorization: authHeader,
Accept: "*/*",
},
}).then((response) => {
// Handle response, e.g., validate status code, body, etc.
return response;
});
};
// Call getApplicationIdByName to get the application ID
return getApplicationIdByName(appNameFilter)
.then((applicationId) => {
// If applicationId is available, delete the application
if (applicationId) {
return deleteApplicationById(applicationId);
} else {
// Handle the case where applicationId is not available
// (e.g., application not found)
cy.log("Application not found.");
return null;
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment