Trying to set up Cypress to test an application that uses OAuth against Azure AD. My login command is defined as follows:
Cypress.Commands.add('login', () => {
return cy.request('POST', Cypress.env('AccessTokenUrl') +
'?grant_type=' + Cypress.env('GrantType') +
'&client_id=' + Cypress.env('ClientId') +
'&client_secret=' + Cypress.env('ClientSecret'))
})
This is what I call in a test:
cy.login().then(response => {
expect(response.status).to.eq(200)
expect(response.body).to.have.property('access_token')
expect(response.body).to.have.property('token_type', 'Bearer')
const {access_token, expires_in, id_token} = response.body
cy.setCookie('access_token', access_token)
})
cy.visit('my-url')
The validations pass. The login response contains a valid token. However, the ct.visit call fails with infinite recursion, as the parameters like &iframe-request-id=[some uuid] become added over and over to a login.microsoftonline.com URL, until eventually returning HTTP Error 414. The request URL is too long.
Here's what the URL looks like, with some information redacted and with some formatting for clarity:
https://login.microsoftonline.com/
[tenant-id]/oauth2/v2.0/authorize
?response_type=code
&client_id=[client-id]
&redirect_uri=[my-url]
&scope=openid+profile+email+https%3A%2F%2Fgraph.microsoft.com%2Fuser.read
&iframe-request-id=1a9fdcbd-6b9e-46c8-93e3-ce0edf62b600
&iframe-request-id=b5b5cf2b-e0a6-4d92-9e55-cf32208ab900
&iframe-request-id=8471e17f-1d36-48f7-8419-f54e14b3b100
&iframe-request-id=56113dad-6029-4a37-9758-5828f93f0300
&iframe-request-id=51c06224-98f1-4b83-a8f2-84f8dfe9aa00
&iframe-request-id=09775645-505c-42e0-ac56-1335b5a7ba00
&iframe-request-id=5c98158b-b202-41fe-9d65-8fbfe4e46500
&[and-so-on]
I have found various suggestions on the web about using Puppeteer as a task for Azure AD SSO, but none of them works for my purposes. First, they try to resolve the problem of actually obtaining the token, which I have already solved. Second, they rely on the login URL presenting an HTML form, which is not the case with login.microsoftonline.com.
What do you suggest?
UPDATE: Trying a different solution, I receive an interesting error. The loginMS command:
import * as MSAL from '#azure/msal-browser'
Cypress.Commands.add('loginMS', () => {
cy.request({
method: 'POST',
url: `https://login.microsoftonline.com/${Cypress.env('TenantId')}/oauth2/token`,
form: true,
body: {
scope: Cypress.env('LoginScope'),
client_id: Cypress.env('ClientId'),
client_secret: Cypress.env('ClientSecret'),
redirect_uri: Cypress.env('LoginRedirect'),
grant_type: Cypress.env('GrantType'),
username: Cypress.env('Username'),
password: Cypress.env('Password'),
response_type: 'code'
}
}).then(response => {
console.log(response)
window.localStorage.setItem(`msal.idtoken`, response.body.access_token);
window.localStorage.setItem(`msal.client.info`, MSAL.clientInfo);
})
})
The error is:
Failed to find a valid digest in the 'integrity' attribute for resource
'https://aadcdn.msauth.net/shared/1.0/content/js/OldConvergedLogin_PCore_Up8WrFIk8-TG_eqBz8MSlw2.js'
with computed SHA-256 integrity 'NxfOkHjbTYDy/EOknsK0PMOfym7iLRGY+yBShyznzx4='.
The resource has been blocked.
It realy depends how the application under test handles requests. But I guess you use the adal libary.
With the help of https://mechanicalrock.github.io/2020/05/05/azure-ad-authentication-cypress.html it worked for me in a vuejs application using adal v1.
The important part is
localStorage.setItem("adal.token.keys", `${Cypress.config("clientId")}|`);
localStorage.setItem(`adal.access.token.key${Cypress.config("clientId")}`, ADALToken);
localStorage.setItem(`adal.expiration.key${Cypress.config("clientId")}`, expiresOn);
localStorage.setItem("adal.idtoken", ADALToken);
I actually did not request the token from azure but just copied in what I saw F12 tools as my token when using the application under test.
I managed to solve the Azure AD login by creating the following Cypress custom command for my Angular application:
Cypress.Commands.add('login', () => {
return cy
.request({
method: 'POST',
url: `https://login.microsoftonline.com/${tenantId}/oauth2/token`,
form: true,
body: {
grant_type: 'password',
tenant: 'tenantId',
client_id: 'clientId',
client_secret: 'clientSecret',
username: 'username',
password: 'password',
resource: 'clientId',
},
})
.then((response) => {
sessionStorage.setItem('access_token', response.body.access_token);
});
});
Related
The ultimate goal (which works if clientId is provided and scopes are clicked): Use Swagger UI to get the azure Auth to receive an accessToken for further requests.
Since the client_id and scopes are static I was hoping to bypass the popup and immediately trigger what happens when clicked on the Authorize button by pre setting the client_id and scopes, since I couldn't find anything there I am atleast trying to pre fill the form so the user only has to click Authorize in my organisation.
What I tried without success:
swagger options initOAuth
DocumentBuilder.components.requestBodies
The Code in main.ts of nestjs:
// Swagger
const config = new DocumentBuilder()
.setTitle('Auth Backend')
.setDescription('Azure PoC backend')
.setVersion('0.1')
.addTag('auth')
.addOAuth2({
type: "oauth2",
description: "description",
name: "AzureAD",
flows: {
implicit: {
scopes: { "User.Read": "Read user profile" },
authorizationUrl: `https://login.microsoftonline.com/${process.env.TENANT_ID}/oauth2/v2.0/authorize`,
}
}
}, "AzureAD")
.build()
const document = SwaggerModule.createDocument(app, config)
SwaggerModule.setup('swagger', app, document, {initOAuth: {clientId: process.env.CLIENT_ID, clientSecret: process.env.CLIENT_SECRET}});
Please try by including swaggerOptions in SwaggerModule.setup which can pass swaggerOptions into swaggerUi.generateHTML
SwaggerModule.setup('api', app, document, { customSiteTitle: 'Your API name', swaggerOptions: {
oauth: {
clientId: clientid",
clientSecret: "clientsecret",
realm: "your-realms",
appName: " ",
scopeSeparator: " ",
scopes: ["User.Read", "profile",”offline_access”],
…. },
persistAuthorization: true, }, });
For the latest versions: ( as given by #julianklumpers in Access swagger-ui after setup to initialize oauth2 -nest.js· Issue · GitHub)
SwaggerModule.setup('api', app, document, {
customSiteTitle: 'API',
swaggerOptions: {
persistAuthorization: true,
oauth2RedirectUrl: 'https://…….’,
initOAuth: {
ClientId,
ClientSecret,
scopes: ["User.Read", "profile",”offline_access”],
appName: ‘name of the app',
},
},
});
Reference: swagger-ui oauth2 · GitHub
In Cypress I am using cy.route() for sending the below request, but cypress is not identifying the below request send. In the route url there is a openHash value which will be different for every POST request. Is there any way to ignore the openHash value or accept what ever value displays there.
So far I have tried by giving the url in following ways in route.
url: '**/student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=**',
url: '**/student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=**&ajaxCall=true**',
I believe while using cy.route() the POST url need to match exactly. Could someone please advise
Cypress version: 5.4.0
Student.feature
Feature: Update student details
Background: User logged in to application
Given I should load all of the routes required for tests
Scenario: Update student details
When I am logged in as the student user
And I click on "Student" subtab
And I should see details displayed
Step definition:
import { Then, When, And } from "cypress-cucumber-preprocessor/steps";
before(() => {
Then('I should load all of the routes required for tests', () => {
cy.server();
cy.route({
method: 'POST',
url: '**student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=5fc8329a76e73&ajaxCall=true**',
delay: 2000
}).as('getStudentTabDetails');
})
})
Then('I am logged in as the student user', () => {
cy.get('[name=loginUsername]').type("Student1");
cy.get('[name=loginPassword]').type("somePassword1", { sensitive: true });
cy.contains('Login').click();
})
Then('I click on {string} subtab', (student) => {
cy.get('#main a').contains(student).click({force:true});
});
Then('I should see details displayed', () => {
cy.wait('#getStudentTabDetails', { timeout: 5000 });
});
Error:
CypressError
Timed out retrying: cy.wait() timed out waiting 5000ms for the 1st request to the route: getStudentTabDetails. No request ever occurred.
Cypress.minimatch is a tool that can be used for checking the route matchers.
By default Cypress uses minimatch to test glob patterns against request URLs.
If you’re struggling with writing the correct pattern you can iterate much faster by testing directly in your Developer Tools console.
The two routes you show in the question actually pass the minimatch test.
const url = 'http://example/student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=5fc8329a76e73&ajaxCall=true';
const pattern1 = '**/student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=**';
console.log( Cypress.minimatch(url, pattern1) ); // true
const pattern2 = '**/student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=**&ajaxCall=true**';
console.log( Cypress.minimatch(url, pattern2) ); // true
Here is a Cypress fiddle that shows how to use the new intercept method to handle query parameters.
/// <reference types="#cypress/fiddle" />
const test = {
html: `
<p class="text-lg"></p>
<script>
setTimeout(() => {
const url = 'http://example/student/details.php?viewDetails=project&stdCount=1§ionID=1&openHash=5fc8329a76e73&ajaxCall=true';
window.fetch(url, { method: 'POST'});
}, 1000);
</script>
`,
test: `
cy.intercept({
method: 'POST',
url: '/student/details.php',
query: {
viewDetails: 'project', // whatever query parts you care about
stdCount: '1',
sectionID: '1'
}
}, {}) // Added an empty stub here, as my url does not actually exist
.as('getStudentTabDetails');
cy.wait('#getStudentTabDetails')
`
}
it('', () => {
cy.runExample(test)
});
The POST is made with native fetch(), which would not be captured in the old cy.route() method without using a polyfill.
I am using react-adminframework, and I have written my own DataProvider. I am trying to accomplish that when an User is created, an instance of UserPossession is created as well. My code bellow accomplishes that, but react-admin Front-end just displays the warning message:
Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body
I checked the Network tab in Developer Tools and every request to server is correct, there is no error. Which leaves me confused and stuck with this, because I have no idea what that warning means or why is it even occuring.
My code is a part of convertDataRequestToHTTP constant and looks like this:
if (resource === 'User') {
url = `${apiUrl}/${resource}`;
options.body = params.data;
httpClient(url, {
method: 'POST',
body: JSON.stringify(options.body),
})
.then(response => (
url = `${apiUrl}/Location`,
options.method = 'POST',
options.body = JSON.stringify({
"odata.type": "HardwareDatabase.UserPossession",
"Name": response.json.Login,
"UserId": response.json.Id
}),
httpClient(url, {
method: options.method,
body: options.body
})
));
}
If you have any questions regarding the code I can clarify.
Thank you for any ideas in advance.
Since you are stating that this code snippet is a part of convertDataRequestToHTTP I might see the issue. httpClient cannot be used in this constant since it creates duplicit calls to API or in your case, this Warning. Correct way would be to only state the options constant.
url = `${apiUrl}/${resource}`;
options.body = JSON.stringifiy(params.data);
options.method = 'POST';
Later in the constant that converts response from OData to mandatory React Admin format, state the httpClient.
params.data = {
"odata.type": "HardwareDatabase.UserPossession",
"Name": response.json.Login,
"UserId": response.json.Id
};
httpClient(`${apiUrl}/Location`, {
method: 'POST',
body: JSON.stringify(params.data),
})
Unfortunately, the GET method for XMLHttpRequest and fetch don't support request bodies.
A temporary work around I found was to use the axios library, which does let you send GET with request bodies.
const res = await axios.get("/api/devices", {
data: { deviceName: 'name' }
})
I am a bit new to VueJS and I am using Laravel as API only and VueJS as a separate project.
In my App.vue, I have following setup:
http://api.com is my virtual host!
<script>
import axios from 'axios';
export default {
data () {
return {
}
},
created() {
const postData = {
grant_type: "password",
client_id: 2,
client_secret: 'MvEyvm3MMr0VJ5BlrJyzoKzsjmrVpAXp9FxJHsau',
username: 'mail#gmail.com',
password: '**********',
scope: ''
}
axios.post('http://api.com/oauth/token', postData)
.then(response => {
const header = {
'Accept': 'application/json',
'Authorization': 'Bearer ' + response.data.access_token,
};
axios.get('http://api.com/api/user', { headers: header })
.then(response => {
console.log(response.data)
})
})
}
}
</script>
But this file is totally visible to front-end which is not good due to security reasons.
What I did, I made a new route in Laravel as Route::post('get_client_creds', MyController#index); and then made a request from axios as:
axios.post('http://api.com/get_client_creds')
.then(response => {
this.client_secret = response.client_secret;
});
And but then I thought anyone can also access the route using Postman or may be through console using axois, so can someone give me some suggestions about where to store these secrets???
Thanks in Advance!
There are two different ways to specify config settings for vue
#1 Vue.js non-cli projects, you can use src/config.js
Create a new file src/config.js and add as following
export const API_CLIENT_ID = '123654';
To use this, try import like:
import { API_CLIENT_ID } from '../config'
// in your code
console.log(API_CLIENT_ID);
#2 For Vue CLi projects follow these steps.
You must use the .env files hold the configuration variables.
It could be structured like
.env # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git
Here is how you can specify the variable.
FOO=bar
API_CLIENT_ID=123456
And you can use this as:
console.log(process.env.API_CLIENT_ID)
Please follow the documentation for more details.
https://cli.vuejs.org/guide/mode-and-env.html#environment-variables
This is my code. I am using authenticate('google'). After clicking on allow button I get error 404.
I am using satellizer.js for google authentication.
Please help me if you understand this error.
Error in browser
POST http://localhost:8080/auth/google 404 (Not Found)
Object {data: "Cannot POST /auth/google↵", status: 404, config: Object, statusText: "Not Found"}
Inside controller
$scope.authenticate = function (provider) {
$auth.link(provider)
.then(function(response) {
// You have successfully linked an account.
console.log(response);
})
.catch(function(response) {
// Handle errors here.
console.log('----------error--------')
console.log(response);
});
};
My code inside app.js
$authProvider.google({
clientId: 'xxxxxxxxxx2op4madn.apps.googleusercontent.com'
});
$authProvider.google({
url: '/auth/google',
authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',
redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,
requiredUrlParams: ['scope'],
optionalUrlParams: ['display'],
scope: ['profile', 'email'],
scopePrefix: 'openid',
scopeDelimiter: ' ',
display: 'popup',
type: '2.0',
popupOptions: {width: 452, height: 633}
});
I got the issue actually it's find a post request on that URL you can add some configuration inside you server.js file follow this given GIT-URL.
github satellizer