API Testing : Check auth handling

Verify that the API correctly handles authentication and authorization and returns the correct HTTP status code.

Language: Java

Framework: Rest assured

copy
1import org.testng.annotations.Test;2import io.restassured.RestAssured.*;3import io.restassured.matcher.ResponseAwareMatcher.*;4import io.restassured.matcher.RestAssuredMatchers.*;5import static org.hamcrest.Matchers.*;67public class APITest {8 9 @Test10 public void testAPIAuthHandling() {11 /​/​Assuming that the API uses JWT for authentication and that a valid token is required for authorized requests12 given().13 header("Authorization", "Bearer <valid_token>").14 when().15 get("/​api/​endpoint").16 then().17 assertThat().statusCode(200);18 19 /​/​Assuming that the API returns a 401 status code for unauthorized requests20 given().21 header("Authorization", "Bearer <invalid_token>").22 when().23 get("/​api/​endpoint").24 then().25 assertThat().statusCode(401);26 27 /​/​Assuming that the API returns a 403 status code for unauthorized actions28 given().29 header("Authorization", "Bearer <valid_token>").30 param("action", "delete").31 when().32 post("/​api/​endpoint").33 then().34 assertThat().statusCode(403);35 36 /​/​Assuming that the API returns a 404 status code for invalid routes37 given().38 header("Authorization", "Bearer <valid_token>").39 when().40 get("/​api/​invalid").41 then().42 assertThat().statusCode(404);43 44 /​/​Assuming that the API returns a 500 status code for server errors45 given().46 header("Authorization", "Bearer <valid_token>").47 when().48 get("/​api/​server-error").49 then().50 assertThat().statusCode(500);51 52 /​/​Assuming that the API returns the expected data for authorized requests53 given().54 header("Authorization", "Bearer <valid_token>").55 when().56 get("/​api/​endpoint").57 then().58 assertThat().body("data.key", equalTo("expected_value"));59 60 /​/​Assuming that the API returns the expected error message for unauthorized requests61 given().62 header("Authorization", "Bearer <invalid_token>").63 when().64 get("/​api/​endpoint").65 then().66 assertThat().body("error.message", equalTo("Unauthorized"));67 68 /​/​Assuming that the API returns the expected error message for server errors69 given().70 header("Authorization", "Bearer <valid_token>").71 when().72 get("/​api/​server-error").73 then().74 assertThat().body("error.message", equalTo("Internal Server Error"));75 76 /​/​Assuming that the API response time is within an acceptable range77 given().78 header("Authorization", "Bearer <valid_token>").79 when().80 get("/​api/​endpoint").81 then().82 assertThat().time(lessThan(5000L));83 84 /​/​Assuming that the API returns the expected JSON schema for authorized requests85 given().86 header("Authorization", "Bearer <valid_token>").87 when().88 get("/​api/​endpoint").89 then().90 assertThat().body(matchesJsonSchemaInClasspath("expected_schema.json"));91 92 /​* Uncomment the code below to connect to a remote client with desired capabilities93 DesiredCapabilities capabilities = new DesiredCapabilities();94 capabilities.setBrowserName("chrome");95 capabilities.setVersion("91");96 capabilities.setCapability("enableVNC", true);97 capabilities.setCapability("enableVideo", false);98 capabilities.setCapability("screenResolution", "1366x768");99 RemoteWebDriver driver = new RemoteWebDriver(new URL("<remote_client_url>"), capabilities);100 */​ 101 }102}

Language: Javascript

copy
1/​/​ Mocha and Chai23/​/​Assuming the API requires token authentication45const chai = require('chai');6const chaiHttp = require('chai-http');7const expect = chai.expect;89chai.use(chaiHttp);1011describe('Authentication Handling Test', function () {12 it('Returns a 401 Unauthorized status code if no token is provided', function (done) {13 chai.request('localhost:3000')14 .get('/​api/​v1/​test')15 .end(function (err, res) {16 expect(res).to.have.status(401);17 done();18 });19 });2021 it('Returns a 403 Forbidden status code if the token is invalid', function (done) {22 const token = 'invalid-token';23 chai.request('localhost:3000')24 .get('/​api/​v1/​test')25 .set('Authorization', 'Bearer ' + token)26 .end(function (err, res) {27 expect(res).to.have.status(403);28 done();29 });30 });3132 it('Returns a 200OK status code if the token is valid', function (done) {33 const token = 'valid-token';34 chai.request('localhost:3000')35 .get('/​api/​v1/​test')36 .set('Authorization', 'Bearer ' + token)37 .end(function (err, res) {38 expect(res).to.have.status(200);39 done();40 });41 });42});4344/​/​Remote client with desired capabilities45/​*46const { Builder } = require("selenium-webdriver");47const firefox = require("selenium-webdriver/​firefox");48const options = new firefox.Options();49options.setPreference("browser.privatebrowsing.autostart", true);50options.setPreference("security.insecure_field_warning.contextual.enabled", false);5152(async function example() {53 let driver = await new Builder()54 .forBrowser("firefox")55 .setFirefoxOptions(options)56 .usingServer("http:/​/​localhost:4444/​wd/​hub")57 .build();58 try {59 /​/​ Test Code Here60 } finally {61 await driver.quit();62 }63})();64*/​

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