<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Salih Emre Boga on Medium]]></title>
        <description><![CDATA[Stories by Salih Emre Boga on Medium]]></description>
        <link>https://medium.com/@s.emre.boga?source=rss-b41855b92525------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yhXqNmeMDJFs-x1wh0lB0w.jpeg</url>
            <title>Stories by Salih Emre Boga on Medium</title>
            <link>https://medium.com/@s.emre.boga?source=rss-b41855b92525------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 01:13:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@s.emre.boga/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Authentication Optimization in Cypress]]></title>
            <link>https://medium.com/picus-security-engineering/authentication-optimization-in-cypress-cddc241bf95e?source=rss-b41855b92525------2</link>
            <guid isPermaLink="false">https://medium.com/p/cddc241bf95e</guid>
            <category><![CDATA[automated-testing]]></category>
            <category><![CDATA[e2e-testing]]></category>
            <category><![CDATA[cypress]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Salih Emre Boga]]></dc:creator>
            <pubDate>Thu, 21 Dec 2023 12:24:19 GMT</pubDate>
            <atom:updated>2023-12-21T12:24:19.923Z</atom:updated>
            <content:encoded><![CDATA[<p>Cypress is a powerful and flexible tool for testing modern web applications. In this article, we will explore the most effective ways to optimize authentication processes in Cypress so that you can make your tests faster and more efficient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fSFGRalbSURpdUAK" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Authentication Optimization?</h3><p>Authentication optimization in Cypress focuses on enhancing the efficiency and speed of tasks related to user authentication within Cypress tests. Authentication, the verification process of a user’s identity, typically includes actions like logging in and handling user sessions. In Cypress testing, authentication processes can act as a bottleneck, resulting in extended test durations.</p><p><strong>The goal of optimizing authentication</strong> in Cypress is to simplify and expedite the login and session management procedures. Developers strive to make these processes faster and more effective, which is essential for improving the overall performance of test suites. This becomes particularly crucial when working with applications that necessitate frequent login/logout operations.</p><p>Let’s start examining the common strategies used to optimize authentication in Cypress.</p><h4><strong>1) Reduce login process count</strong></h4><p>The login process typically simulates a user authentication process, providing access to specific pages or features. If your application requires a user to log in, and your test scenarios rely on this login process, then performing the login before each test scenario can make your tests more realistic and reflective of actual usage.</p><p>However, there are potential drawbacks to performing the login before each test scenario. For instance, overheads from login durations cumulatively increase as new test scenarios are added. If the actions to be tested can be consolidated, combining tests can reduce the overall test time. Not performing a login before each scenario can also decrease the independence of test scenarios, as the failure of a preceding scenario could impact subsequent ones.</p><p>The decision to perform a login before each test scenario depends on your application’s requirements, the structure of your test scenarios, and your objectives. In some cases, the login process may only be necessary for specific scenarios, or login states may be shared among test scenarios.</p><h4>2) Differentiate authentication method</h4><p>In Cypress, authentication processes are often repeated in each test, leading test developers to attempt logging in from the application’s login page. However, this may not be the best solution.</p><p>On an example login page, let’s assume a situation where the username and password fields are filled in and the login button is pressed.</p><pre>Cypress.Commands.add(&quot;login&quot;, (email, password) =&gt; {<br> cy.visit(&quot;/&quot;)<br> cy.get(&quot;#username&quot;).type(username)<br> cy.get(&quot;#password&quot;).type(password)<br> cy.get(&quot;#loginButton&quot;).should(&quot;not.disabled&quot;).click()<br> cy.url().should(&quot;not.contain&quot;, &quot;/signin&quot;)<br>})</pre><p>First, you need to wait for the page to open. After waiting for the username and password input fields to be rendered, you will also need to wait for the values to be written to the input fields. Due to the time-consuming nature of this process, directing the user to the login page for each test and performing authentication operations on the screen reduces the usability of the tests.</p><p>As a solution to the above problem, <strong>“intercept”</strong> and <strong>“request”</strong> commands used for Cypress’s network controls can be used without opening the login page before starting the test.</p><pre>Cypress.Commands.add(&quot;loginWithRequest&quot;, (email, password) =&gt; {<br> cy.intercept(&#39;GET&#39;, &quot;/auth/is-logged-in&quot;).as(&#39;logged-in&#39;)<br> cy.request({<br>  method: &quot;POST&quot;,<br>  url: &quot;/auth/login&quot;,<br>  body: { email, password },<br> }).then((response) =&gt; {<br> cy.setCookie(&quot;sessionId&quot;, response.body.sessionId)<br> cy.setCookie(&quot;userId&quot;, response.body.userId)<br> cy.setCookie(&quot;username&quot;, response.body.userName)<br>   })<br>})<br>cy.wait(&quot;@logged-in&quot;)<br>cy.visit(&quot;/&quot;)</pre><p>So let’s see what’s going on here.</p><ol><li>First, the intercept method is used. With this method, you can listen to all requests made in your application and shape your test according to the results. The first request I send after the login process is listened to with the <strong>“intercept”</strong> method and written to an alias for later use.</li><li>Then came the part that does the real work. While the application is being logged in, a POST request is sent to the endpoint with the <strong>“request”</strong> method. Username and password properties are passed to the body.</li><li>The cy.setCookie functionality is employed in the body of this arrow function to have certain cookies set based on the content of the request-response. These cookies are specifically the ones set when a user logs in through the graphical user interface.</li><li>Response time is waited and the page is redirected.</li></ol><p>Some problems may be encountered when accessing the server via Cypress. Due to some security concerns, your backend servers may filter incoming requests. In this case, before the tests start, you can put a secret key in the headers of the requests going through Cypress. Then you can specify this keyword in your backend configs so that you will know you are receiving these requests from Cypress. A code example for this can be seen below:</p><pre>beforeEach(() =&gt; {<br> const rnd = cy.id.substr(2)<br> cy.intercept({ url: `${Cypress.config(&quot;baseUrl&quot;)}**`, middleware: true }, (req) =&gt; {<br>  req.headers[&quot;Cypress_Test_Secret&quot;] = &quot;cypress&quot;<br>  req.headers[&quot;X-Forwarded-For&quot;] = `1.1.1.${rnd}`<br>  return req<br> }).as(&quot;headers&quot;)<br>})</pre><h4><strong>3) Use cache mechanism to authenticate with cy.session</strong></h4><p>There is a method to both obtain a clean test scenario and avoid performing a login process at the beginning of each test scenario. Cypress introduced the cy.session feature with version 8.2.0. This new feature enables refreshing and preserving cookies, local storage, and session storage. With this feature, the login process will only be executed once if user credentials remain unchanged. Subsequent operations will utilize the session information cached, and it will be retrieved from the cache for the following processes. Let&#39;s examine this with a more detailed example.</p><pre>Cypress.Commands.add(&quot;restoreLogin&quot;, (email, password) =&gt; {<br> cy.session([email, password], () =&gt; {<br>  cy.visit(&quot;/&quot;)<br>  cy.request({<br>   method: &quot;POST&quot;,<br>   url: &quot;/auth/login&quot;,<br>   body: { email, password },<br>  })<br> })<br>})</pre><p>The cy.session operation takes login credentials as its first parameter. The subsequent function, which will be executed, is the core function responsible for the login process. In reality, the cy.session operation doesn&#39;t perform the login process itself; it merely facilitates the caching of cookie and session information. It continues to use this cached information, mapping it with the entered credentials, for subsequent login processes.</p><p>To maintain consistent session states, cy.visit(&quot;/&quot;) call should be made. The reason for this is that the cy.session operation cleans the page, altering the state of both the application and the test. Therefore, a redirection to the home page is performed for this purpose.</p><p>Let’s consider a test scenario where different users are involved. For example, let’s have the user1, who is an admin, change the role of another user, and perform this test in a single scenario.</p><pre>it(&#39;enter new user role&#39;, () =&gt; {<br>  cy.restoreLogin(&#39;user1&#39;, &#39;password1&#39;)<br>  cy.get(&#39;#user-input&#39;).type(&#39;user2&#39;)<br>  cy.get(&#39;#role-input&#39;).type(&#39;New Role&#39;)<br>  cy.get(&#39;#create-role&#39;).click()<br><br>  //there is no need for logout. Because we will change user<br>  <br>  cy.restoreLogin(&#39;user2&#39;, &#39;password2&#39;)<br>  cy.get(&#39;#assigned-role&#39;).should(&#39;eq&#39;, &#39;New Role&#39;)<br>})</pre><p>user1 replaces the role information of user2 at the beginning of the scenario. Later in the test, user2 logs in and this new role value is checked. After the first user transaction, the checks are ensured correctly by logging in with the second user without logging out with this user. This improves test performance by avoiding the need to write a separate test. Since the changes made by two users regarding the roles are checked, the scenario maintains its integrity even if it becomes more detailed.</p><p>Different users needing to log in can be handled with the caching method used. When cy.session is called, the current session is cleared, and the provided login function is executed. Since the current session is cleared, a clean login process can be performed with the login credentials provided for the next user. The need to log out the previous user is eliminated.</p><p>This way, new users don’t log in one after the other in the same browser. It provides a usage pattern similar to a customer logging in with a different user in another browser tab. This allows your tests to be closer to real-world usage.</p><p>The cy.session method automatically recognizes when the session has dropped, but in some cases, manual control may be desired. If a validate function is passed as a parameter, this method is queried in each operation, ensuring that the session is handled.</p><p>If the tested users need to be stored and reused, the cacheAcrossSpecs value should be set to true. In this case, previous sessions are kept active until a certain timeout, and they can be used in subsequent tests.</p><h3><strong>Performance Comparison</strong></h3><p>The table below illustrates average test durations based on the authentication method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWi3xVfTorcKvLWeLtyfrQ.png" /></figure><p>When measuring average test durations, testing the login page before each test scenario significantly extends the process. Considering the presence of dozens of tests, the impact can be substantial. Taking into account the effect of caching mechanisms when tests are run consecutively, especially with a large number of tests, the use of cy.session can have a significant impact.</p><h3><strong>Conclusion</strong></h3><p>In conclusion, we summarized the improvements that can be made when performing authentication in Cypress tests. We emphasized the importance of minimizing the <strong>number of logins</strong>, the preference for <strong>not using the login screen for authentication</strong>, and discussed how to manage sessions using the <strong>cy.session</strong> method. We also delved into analyzing the performance of these methods. If, like us, you have a large number of automated tests, have matched your scenarios with various users, and your automated tests are part of the release pipeline, you should definitely implement these improvements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cddc241bf95e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/picus-security-engineering/authentication-optimization-in-cypress-cddc241bf95e">Authentication Optimization in Cypress</a> was originally published in <a href="https://medium.com/picus-security-engineering">Picus Security Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>