跳到主要内容

Request an Interface That Requires Login to Access (Based on COOKIE)

When developing and debugging interfaces in the backend, we often encounter interfaces that require login to request.

For example: to get the list of favorites of the logged-in user, we need to simulate the login state for interface debugging. As shown in the figure:

image.png

Today, we will explain how to use EchoAPI's environment variables to solve the dependency situation where an interface needs to be logged in before requesting.

EchoAPI provides two solutions:

Solution I: Enable global cookies

EchoAPI provides the function to enable global cookies. The enabling path is as follows:

Bottom right corner Cookie Manager - Open Global Cookie button

image.png

image.png After enabling, after we request the login interface, subsequent interfaces will share the "logged in" state, that is, share the cookie returned by the login interface.

As shown below:

Step 1: Request the login interface

image.png

Step 2: Access other interfaces, all of which are in the logged-in state

image.png

Solution II: Use environment variables to request the login interface first, then request subsequent interfaces

This solution is for the situation where the global cookie function is turned off.

To be in the logged-in state, we need to request the login interface first. The purpose of this is to simulate the user's login behavior and obtain the necessary login parameters (here it is the Cookie).

Set the PHPSESSID (this is the SessionID, PHPSESSID is the SessionID variable name for PHP as the backend interface, other languages may have different variable names) returned by the login interface as an environment variable.

pm.variables.set("login_var", response.cookies["PHPSESSID"]);

Note: For more response result binding variables, please refer to the "Response and Assertion" section and the "Post-execution Script" section.

image.png

Then return to the favorites interface, go to the header option, select cookie for the parameter value, and enter: PHPSESSID={{login_var}}.

This is to use the Cookie returned by the login interface to forge the PHPSESSID request.

As shown in the figure:

image.png Or you can define a global header, so you don't have to set it for each interface:

image.png

Login Implementation Principle

Use EchoAPI to send Cookies so that the server recognizes the logged-in user's Cookies.