automated-testsrest-assured

HTTP/1.1 401 Unauthorized with RestAssured


I get HTTP/1.1 401 Unauthorized for subsequent API calls using RestAssured. First call is for login and then license aggrement acceptance. For the same two APIs of another service need to be called. After first API call success response, the second API call, most of the times give 401 error but some times it gives 204. These API call works fine with postman collection.

   @RestController
   @RequestMapping(value = "/url")
   public class AController {

   @ApiOperation(value = "testMethod")
   @GetMapping(value = "testMethod", consumes = "application/json", produces = "application/json")
   public ResponseEntity<String> testMethod()
     throws Throwable {
   //login
    System.out.println(" Login ................ ");
    Map<String, String> loginRequest = new LinkedHashMap<>();
    loginRequest.put("username", "loginname");
    loginRequest.put("password", "pass");
    loginRequest.put("domain", "pass");
    
    Response loginResponse = RestAssured.given().relaxedHTTPSValidation().contentType("application/json")
    .cookie("JSESSIONID", "dummy")
            .body(loginRequest).log().all().when().post("https://ip:port/url")
    .then().log().all().extract().response();
    Cookies coockies =loginResponse.getDetailedCookies();

    //acceptance
    System.out.println("acceptance....................");
    Map<String, String> agreeRequest = new LinkedHashMap<>();
    agreeRequest.put("aggrementAccepted", "Y");

     Response agreeResponse = RestAssured.given().relaxedHTTPSValidation().contentType("application/json")
                        .cookies(cookies)
                        .header("A_COOK2",coockies.getValue("A_COOK2"))
                        .log().all()
                        .body(agreeRequest).when().post("https://ip:port/url")
                        .then().log().all().extract().response();
     return new ResponseEntity<String>(agreeResponse, HttpStatus.OK);
    }
    }

######Log of Request and Response #######

----Error Response for acceptance:
Request method: POST
Request URI:    https://ip:port/url
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        Accept=*/*
Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>
Body:
{
   "username": "loginname",
    "password": "pass",
    "domain": "pass"
 }
 HTTP/1.1 200 OK
 Content-Security-Policy: script-src 'self' 'unsafe-inline' 'unsafe- 
  eval'; style-src 'self' 'unsafe-inline'
  Cache-Control: no-store, no-cache, must-revalidate
  Pragma: no-cache
  X-Content-Type-Options: nosniff
  Strict-Transport-Security: max-age=15768000
  X-Download-Options: noopen
  X-XSS-Protection: 1; mode=block
  X-FRAME-OPTIONS: SAMEORIGIN
  transfer-encoding: chunked
  Content-Type: application/json; charset=utf-8
  setcookie: A_COOK2= p29YwlWxWXhZGO1ZgLew2/z4jWZxo3hMnkepe
  JOEENILyRNbKv1pOSOY7Zr25g8jAHqtyhUjFkw3i7jD5Y9IcYu+OuA=; Path=/; 
  Secure
  set-cookie: A_COOK1 =bqvRVooK7RXQMBC98EYrX1uS8IyPlaT4
    dSHyjXC81lJFoZdU0ihYiDtZ893fL6hm5r2V7c+CgfY1Ds2f6RF 
    VGaGYe7VT4h4m27ATrl7lRZOecFprdTWdpOQ+UG2htcauUAVuW 
    Heqr1NL4glhrloEYQ==; Path=/; Secure;
  HTTPOnly
   {
      "userName": "loginname",
       "role": "Admins",
       "appMode": "APPL",
       "isRegistrationDone": false,
       "exp": "2022-04-01T01:35:07.000Z",
       "currentSystemTime": "2022-04-01T01:05:07.082Z"
    }
  acceptance....................
  Request method:   POST
  Request URI:  https://ip:port/url
  Proxy:            <none>
  Request params:   <none>
  Query params: <none>
  Form params:  <none>
  Path params:  <none>
  Headers:       A_COOK2=p29YwlWxWXhZGO1ZgLew2/z4jWZxo3hMnkepe 
  JOEENILyRNbKv1pOSOY7Zr25g8jAHqtyhUjFkw3i7jD5Y9IcYu+OuA=
  Accept=*/*
  Content-Type=application/json; charset=UTF-8
  Cookies:      A_COOK2=p29YwlWxWXhZGO1ZgLew2/z4jWZxo3 
  hMnkepeJOEENILyRNbKv1pOSOY7Zr25g8jAHqtyhUjFkw3i 
  7jD5Y9IcYu+OuA=;Path=/;Secure
  A_COOK1=bqvRVooK7RXQMBC98EYrX1uS8IyPlaT4dSHyjXC81l 
  JFoZdU0ihYiDtZ893fL6hm5r2V7c+ 
  CgfY1Ds2f6RFVGaGYe7VT4h4m27ATrl7lRZOecFprdTW 
  dpOQ+UG2htcauUAVuWHeqr1NL4glhrloEYQ==;Path=/;Secure;HttpOnly
  Multiparts:       <none>
  Body:
 {
    "aggrementAccepted": "Y"
 }
 HTTP/1.1 401 Unauthorized
 Content-Type: application/json
 content-length: 230
{
  "type": "ERROR",
  "code": "A-080003",
  "message": "We couldn't continue with this authorization key. Enter 
  a new key, then try again.",
  "details": {
    "responseAction": "",
    "detailedDescription": "",
    "additionalErrors": [
        
    ],
    "additionalInfo": {
        
      }
   }
 }


---Success Response for acceptance:

Request method: POST
Request URI:    https://ip:port/url
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        Accept=*/*
            Content-Type=application/json; charset=UTF-8
Cookies:        <none>
Multiparts:     <none>
Body:
{
   "username": "loginname",
   "password": "pass",
   "domain": "pass"
 }
HTTP/1.1 200 OK
Content-Security-Policy: script-src 'self' 'unsafe-inline' 'unsafe- 
eval'; style-src  'self' 'unsafe-inline'
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=15768000
X-Download-Options: noopen
X-XSS-Protection: 1; mode=block
X-FRAME-OPTIONS: SAMEORIGIN
transfer-encoding: chunked
Content-Type: application/json; charset=utf-8
set-cookie: A_COOK2=p29YwlWxWXhZGO1ZgLew2/z4jWZxo3hMnkepe 
JOEENILyRNbKv1pOSOY7Zr25g8jAHqtyhUjFkw3i7jD5Y9IcYu+OuA=; Path=/; 
Secure
set-cookie:A_COOK1=bqvRVooK7RXQMBC98EYrX1uS8IyPlaT4dSHyjXC81l 
JFoZdU0ihYiDtZ893fL6hm5r2V7c+CgfY1Ds2f6RFVGaGYe 
7VT4h4m27ATrl7lRZOecFprdTWdpOQ+UG2htcauUAVuWHeqr1NL4glhrloEYQ==; 
Path=/; Secure; HTTPOnly
{
  "userName": "loginname",
  "role": "Admins",
  "appMode": "APPL",
  "isRegistrationDone": false,
  "exp": "2022-04-01T01:35:07.000Z",
  "currentSystemTime": "2022-04-01T01:05:07.082Z"
}
acceptance....................
Request method: POST
Request URI:    https://ip:port/url
Proxy:          <none>
Request params: <none>
Query params:   <none>
Form params:    <none>
Path params:    <none>
Headers:        A_COOK2=p29YwlWxWXhZGO1ZgLew2/z4jWZxo3hMnkepeJOEENIL 
yRNbKv1pOSOY7Zr25g8jAHqtyhUjFkw3i7jD5Y9IcYu+OuA=
Accept=*/*
Content-Type=application/json; charset=UTF-8
Cookies:A_COOK2=p29YwlWxWXhZGO1ZgLew2/z4jWZxo3hMnkepeJOEENI 
LyRNbKv1pOSOY7Zr25g8jAHqtyhUjFkw3i7jD5Y9IcYu+OuA=;Path=/;Secure
A_COOK1=bqvRVooK7RXQMBC98EYrX1uS8IyPlaT4dSHyjXC81 
lJFoZdU0ihYiDtZ893fL6hm5r2V7c+CgfY1Ds2f6RFVGa 
GYe7VT4h4m27ATrl7lRZOecFprdTWdpOQ+UG2htcauUAV 
uWHeqr1NL4glhrloEYQ==;Path=/;Secure;HttpOnly
Multiparts:     <none>
Body:
{
  "aggrementAccepted": "Y"
}
HTTP/1.1 204 No Content
Content-Security-Policy: script-src 'self' 'unsafe-inline' 'unsafe- 
eval'; style-src 'self' 'unsafe-inline'
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=15768000
X-Download-Options: noopen
X-XSS-Protection: 1; mode=block
X-FRAME-OPTIONS: SAMEORIGIN
Content-Type: application/json; charset=utf-8

Solution

  • String loginCookie2= loginResponse.getCookie("A_COOK2");
    
    String loginCookie1= loginResponse.getCookie("A_COOK1");
    
    .header("A_COOK2", URLEncoder.encode(loginCookie2, String.valueOf(StandardCharsets.UTF_8)))
    .cookie("A_COOK1", loginCookie1).urlEncodingEnabled(true)
    

    Used header and cookie with URLEncode and it is working now.