1

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!

1 Answer 1

3

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}")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.