API Testing : Check CSRF prevention

Verify that the API correctly handles cross-site request forgery (CSRF) prevention and returns the correct HTTP status code and error message.

Language: Java

Framework: Rest assured

copy
1import static io.restassured.RestAssured.*;2import static org.hamcrest.Matchers.*;34public class CSRDPreventionTest {56 @Test7 public void testCSRFPrevention() {89 /​/​Assuming API endpoint URL10 String endpointURL = "http:/​/​myapi.com/​csrfPrevention";11 12 /​/​Assuming a sample CSRF token13 String csrfToken = "123ABC";14 15 /​/​Assuming a sample request body16 String requestBody = "{ \"username\":\"testuser\", \"password\":\"testpass\", \"csrfToken\":\""+csrfToken+"\"} ";17 18 /​/​Assuming the expected status code in case of success19 int expectedSuccessStatusCode = 200;20 21 /​/​Assuming the expected error message in case of failure22 String expectedFailureMessage = "CSRF verification failed. Request aborted.";23 24 /​/​Sending the POST request with the CSRF token25 given()26 .contentType("application/​json")27 .body(requestBody)28 .post(endpointURL)29 .then()30 .assertThat()31 .statusCode(expectedSuccessStatusCode)32 .body("message", is("CSRF verification successful."));33 34 /​/​Sending the POST request without the CSRF token35 given()36 .contentType("application/​json")37 .body("{ \"username\":\"testuser\", \"password\":\"testpass\", \"csrfToken\":\"\"} ")38 .post(endpointURL)39 .then()40 .assertThat()41 .statusCode(401)42 .body("message", is(expectedFailureMessage));43 44 /​/​Code to use remote client with desired capabilities45 /​*46 DesiredCapabilities capabilities = new DesiredCapabilities();47 capabilities.setCapability("platformName", "iOS");48 capabilities.setCapability("deviceName", "iPhone 11");49 capabilities.setCapability("browserName", "Safari");50 capabilities.setCapability("version", "14.1");51 capabilities.setCapability("name", "CSRF Prevention API Test");5253 WebDriver driver = new RemoteWebDriver(new URL("http:/​/​localhost:4723/​wd/​hub"), capabilities);54 */​55 }56}

Language: Javascript

copy
1/​/​ Mocha with Chai. 23Assumption: The API is hosted on a local server and can be accessed via http:/​/​localhost:3000. 45/​/​Import necessary libraries6const chai = require('chai');7const chaiHttp = require('chai-http');8const app = require('../​app');910/​/​Configure chai11chai.use(chaiHttp);12chai.should();1314/​/​Test Suite for CSRF Prevention15describe('API CSRF Prevention Test', () => {1617 /​/​Test to verify API returns 403 status code for CSRF attack18 it('Should return 403 status code for CSRF attack', (done) => {19 chai.request(app)20 .post('/​login')21 /​/​Assuming an invalid CSRF token is used22 .set('X-CSRF-Token', 'invalidToken')23 .end((err, res) => {24 res.should.have.status(403);25 res.body.should.have.property('message')26 .equal('CSRF Attack detected. Request not authorized.');27 done();28 });29 });3031 /​/​Test to verify API returns 200 status code for valid request32 it('Should return 200 status code for valid request', (done) => {33 chai.request(app)34 .post('/​login')35 /​/​Assuming a valid CSRF token is used36 .set('X-CSRF-Token', 'validToken')37 .end((err, res) => {38 res.should.have.status(200);39 res.body.should.have.property('message')40 .equal('Login successful.');41 done();42 });43 });44});4546/​/​Code to connect to remote client with desired capabilities47/​*const webdriver = require('selenium-webdriver');48const remote = require('selenium-webdriver/​remote');4950const capabilities = webdriver.Capabilities.edge();5152let driver = new webdriver.Builder()53 .usingServer('http:/​/​example.com:4444/​wd/​hub')54 .withCapabilities(capabilities)55 .build();*/​

Disclaimer: Following code snippets and related information have been sourced from GitHub and/or generated using AI code generation tools. LambdaTest takes no responsibility in the accuracy of the code and is not liable for any damages.

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Power Your Software Testing with AI and cloud

Test Intelligently and ship faster. Deliver unparalleled digital experiences for real world enterprises.

Start Free Testing