Search code examples
akkaakka-http

How to do akka http request for oauth2 access_token


I am trying to request auth server to get access_token . I have a working curl command , but am unable to implement using Akka HTTP.

 curl -v -u CLIENT_ID:CLIENT_SECRET -k -X POST -d {} 'URL/oauth2/token?grant_type=client_credentials&scope=Scope'

or

curl -i -H 'Authorization: Basic Base64(CLIENT_ID:CLIENT_SECRET)' --request POST URL/oauth2/token -d 'grant_type=client_credentials&scope=scope'

i am getting 405 Method Not Allowed error while requesting using http.singleRequest

def getToken(url:String, user: String, pass: String, scope:String) = {

  Http()
    .singleRequest(
      Post(
        Uri(url),
        Map("grant_type" -> "client_credentials", "scope" -> s"$scope"),
      ).withHeaders(
        Authorization(BasicHttpCredentials(user, pass)),
      ),
    )

}

Solution

  • val request = HttpRequest(
      HttpMethods.POST,
      config.authDomain,
      entity = FormData
        .apply(
          Map(
            "grant_type" -> s"${config.grant_type}",
            "scope" -> s"${config.api_scope}",
          ),
        )
        .toEntity,
    ).withHeaders(Authorization(BasicHttpCredentials(config.access_id, config.access_secret)))