</>

Technology

Rest Assured

Difficulty

Intermediate

Interview Question

What is CORS and how do you test CORS in API testing?

Answer

CORS — Cross-Origin Resource Sharing

CORS is a browser security mechanism that restricts web pages from making requests to a different origin (domain, protocol, or port) than the one that served the web page.

Why CORS Exists

CODE
https://myfrontend.com  →  API call →  https://api.backend.com
       (Origin A)                            (Origin B)

Browser blocks this by default unless api.backend.com
explicitly allows requests from myfrontend.com

CORS Headers

HeaderExamplePurpose
Access-Control-Allow-Origin* or https://myfrontend.comAllowed origins
Access-Control-Allow-MethodsGET, POST, PUT, DELETEAllowed HTTP methods
Access-Control-Allow-HeadersContent-Type, AuthorizationAllowed request headers
Access-Control-Max-Age3600Cache preflight for 1 hour

How CORS Works — Preflight Request

For non-simple requests (POST with JSON), browsers send a preflight OPTIONS request first:

CODE
OPTIONS /api/users HTTP/1.1
Origin: https://myfrontend.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization

Response:
Access-Control-Allow-Origin: https://myfrontend.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 3600

Testing CORS in Rest Assured

Java
@Test
public void testCORSHeadersPresent() {

    given()
        .header("Origin", "https://myfrontend.com")
        .when()
        .options("/api/users")
        .then()
        .statusCode(200)
        .header("Access-Control-Allow-Origin", "https://myfrontend.com")
        .header("Access-Control-Allow-Methods", containsString("GET"))
        .header("Access-Control-Allow-Methods", containsString("POST"));
}

@Test
public void testCORSWithUnauthorizedOrigin() {

    given()
        .header("Origin", "https://malicious-site.com")
        .when()
        .options("/api/users")
        .then()
        // Should NOT allow unauthorized origins
        .header("Access-Control-Allow-Origin", not("https://malicious-site.com"));
}

CORS Test Checklist

  • ✅ Allowed origins can make preflight OPTIONS requests
  • Access-Control-Allow-Origin header is present in responses
  • ✅ Wildcard * is NOT used for authenticated endpoints
  • ✅ Unauthorized origins are rejected
  • Access-Control-Allow-Methods includes only necessary methods
  • ✅ Credentials are handled correctly (cookies, auth headers)

Follow AutomateQA

Related Topics