Knowledge Base Article

Dispatching responses from a Virtual Service


Create a REST virtual service with the "GET /login" resource and add a dispatching script, which returns different responses based on the values of query parameters (grant_type, username and password).

A sample request: 



The dispatching condition:

  • If grant_type is not equal to "password", the virt returns the "Unsupported Grant Type" response (HTTP status code is 401, body is {"error": "Unsupported Grant Type"}).
  • If grant_type is equal to "password", but the username is not equal to "test" OR the password doesn't comply with the strength requirements (the minimal length is 8 characters, the password contains at least one uppercase letter, one lowercase letter, one number and one symbol) the virt returns the "Invalid Login Info" response (HTTP status code is 401, body is {"error": "Invalid Username or Password"}).
  • If some parameters are missing, the virt returns the "Bad Request" response (HTTP state code is 400, body is {"error":"required parameters are missed"})
  • If all the parameters have valid values, the virt returns the "OK" response (HTTP status code is 200, body is {"result":"ok"}).




Here is a script that dispatches responses


The idea behind it is pretty simple namely creating one operation, 4 responses and setting the dispatch style to script. The code I used is attached below:


// Get the full query string
def queryString = mockRequest.getRequest().getQueryString()
// Get the password index in the query string
def passwordIndex = queryString.indexOf("password=") + 9
// Cut out the password starting with the previously obtained index
def pass = queryString.substring(passwordIndex)
// If there are more parameters after the password rule them out
if (pass.contains("&"))
	pass = pass.substring(0, pass.indexOf("&"))

 * Start dispatching responses
if( !queryString.contains("grant_type=") || !queryString.contains("username=") || !queryString.contains("password=") )
	// Return a bad request
	return "BadRequest"
 else if ( !queryString.contains("grant_type=password")) 
	// Return an unsupported grant type response
	return "UnsupportedGrantType"	
} else if ( !queryString.contains("username=test") || !checkPasswordComplexity(pass))
	// Return invalid credentials
	return "InvalidCredentials"
} else 
	return "Success"

// Methods definition
def checkPasswordComplexity(String password) 
	if (password ==~ /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}/)
		return true
		return false
Published 3 years ago
Version 1.0

Was this article helpful?

No CommentsBe the first to comment