Home > Net >  Groovy rest client without libraries with basic authentication
Groovy rest client without libraries with basic authentication

Time:12-30

Hello I need to connect to an url using a basic authentication with Groovy, I would prefer to achieve this without using any libraries, because in our project we have scan for vulnerabilities and some times we faced problems when we include a new library. I was following the next examples:

 def connection = new URL( "https://jsonplaceholder.typicode.com/posts")
        .openConnection() as HttpURLConnection

    // set some headers
    connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
    connection.setRequestProperty( 'Accept', 'application/json' )

    // get the response code - automatically sends the request
    println connection.responseCode   ": "   connection.inputStream.text

It worked but in my case I need to connect with a basic authentication (username and password). I haven't seen examples related.

Any ideas?

Thanks!

CodePudding user response:

https://en.wikipedia.org/wiki/Basic_access_authentication

In basic HTTP authentication, a request contains a header field in the form of

Authorization: Basic <credentials>

where <credentials> is the Base64 encoding of ID and password joined by a single colon :.

in groovy it could look like this:

def user = ...
def pass = ...
def auth = "${user}:${pass}".bytes.encodeBase64()
connection.setRequestProperty("Authorization", "Basic ${auth}")
  • Related