API Testing : Check unauthorized requests

Verify that the API returns the correct HTTP status code for unauthorized requests (e.g. HTTP 401 Unauthorized).

Language: Java

Framework: Rest assured

copy
1/​/​Assuming the base API URL is "https:/​/​myapi.com"2/​/​Assuming there is an endpoint "/​user/​profile" that requires authorization to access34import org.junit.jupiter.api.Test;5import io.restassured.RestAssured;6import io.restassured.response.Response;7import static io.restassured.RestAssured.given;8import static org.junit.jupiter.api.Assertions.assertEquals;910public class APITest {1112 @Test13 public void testUnauthorizedRequest() {14 /​/​using local driver15 RestAssured.baseURI = "https:/​/​myapi.com";16 given()17 .when().get("/​user/​profile")18 .then().assertThat().statusCode(401);19 20 /​/​using remote driver21 /​/​DesiredCapabilities capabilities = DesiredCapabilities.chrome();22 /​/​WebDriver driver = new RemoteWebDriver(new URL("http:/​/​localhost:4444/​wd/​hub"), capabilities);23 /​/​RestAssured.baseURI = "https:/​/​myapi.com";24 /​/​Response response = given().header("Authorization", "Bearer <invalid_token>")25 /​/​ .when().get("/​user/​profile")26 /​/​ .then().extract().response();27 /​/​assertEquals(401, response.getStatusCode());28 }29}

Language: Javascript

copy
1/​/​ Mocha and Chai.23/​/​Assuming the API endpoint is "api.example.com"4const apiEndpoint = "https:/​/​api.example.com";56/​/​Assuming the endpoint requires authentication and returns a JSON object with a "status" key7/​/​Setting up local driver8const webdriver = require('selenium-webdriver');9const chrome = require('selenium-webdriver/​chrome');10const chromedriver = require('chromedriver');1112const options = new chrome.Options();13options.addArguments('start-maximized', 'disable-extensions');14const service = new chrome.ServiceBuilder(chromedriver.path).build();15const driver = new webdriver.Builder()16 .forBrowser('chrome')17 .withCapabilities(webdriver.Capabilities.chrome())18 .setChromeOptions(options)19 .build();2021/​/​Commented code for connecting to remote client with desired capabilities 22/​/​ const remoteWebdriver = require('selenium-webdriver/​remote');23/​/​ var remoteCapabilities = {24/​/​ browserName: 'chrome',25/​/​ platform: 'WINDOWS',26/​/​ version: '10'27/​/​ };28/​/​29/​/​ const driver = new webdriver.Builder()30/​/​ .usingServer('http:/​/​localhost:4444/​wd/​hub')31/​/​ .withCapabilities(remoteCapabilities)32/​/​ .build();3334/​/​Performing API testing using Mocha and Chai35describe('API Testing - Check unauthorized requests', function(){36 37 it('should return HTTP 401 Unauthorized status code when no authentication is provided', function(){38 driver.get(`${apiEndpoint}/​unauthorizedRequest`);39 driver.wait(until.elementLocated(By.css('body')), 10000);4041 driver.findElement(By.css('body')).getAttribute('class').then(function(classes){42 /​/​Checking if the status code is 401 Unauthorized43 expect(classes).to.equal('http-401');44 });45 });4647 it('should return HTTP 401 Unauthorized status code when invalid authentication is provided', function(){48 const username = "testuser";49 const password = "testpass";50 driver.get(`${apiEndpoint}/​authorizedRequest`);51 driver.wait(until.elementLocated(By.css('.login-form')), 10000);52 53 /​/​Assuming the authentication details are required to be entered in a form with "username" and "password" input fields54 driver.findElement(By.css('input[name="username"]')).sendKeys(username);55 driver.findElement(By.css('input[name="password"]')).sendKeys(password);56 driver.findElement(By.css('form[name="loginForm"] button[type="submit"]"')).click();57 driver.wait(until.elementLocated(By.css('.response-body')), 10000);5859 /​/​Checking if the status code is 401 Unauthorized60 driver.findElement(By.css('.response-body')).getAttribute('class').then(function(classes){61 expect(classes).to.equal('http-401');62 });63 });64});6566/​/​Closing the driver67driver.quit();

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