简体   繁体   中英

Java REST api authorization issue

I am trying to write a simple app that is conecting with Allegro.pl, but I am stuck on authorization. I have spent way too many hours already trying to figure this out (postman was not helpful), and I wounder if you can have a look and help, please?

As per documentation, all data should be encoded with Base64 - I tried to encode as String as well, as byte[], but authorization fails all the time with an error:

{"error":"Unauthorized","error_description":"Unauthorized"}

in documentation there is a curl code (please disregard different web address, as I am working in a sandbox)

curl -X POST 

  ‘https://allegro.pl/auth/oauth/device' 
  -H ‘Authorization: Basic {base64(client_id:client_secret)}’ 
  -H ‘Content-Type: application/x-www-form-urlencoded’ 
  -d ‘client_id={client_id}’

Please see below for my code

package AllegroAPI;

import kong.unirest.HttpResponse;
import kong.unirest.JsonNode;
import kong.unirest.Unirest;
import org.apache.commons.codec.binary.Base64;

public class App
{
    public static void main( String[] args )
    {
        String clientId = "myClientId";
        String clientSecret = "myClientsSecret";
        String authString = clientId + ":" + clientSecret;

//        String codedAuthString = Base64.encodeBase64String(authString.getBytes());
        byte[] codedAuthString = Base64.encodeBase64(authString.getBytes());
        byte[] codedClientId = Base64.encodeBase64(clientId.getBytes());

        HttpResponse response = Unirest.post("https://allegro.pl.allegrosandbox.pl/auth/oauth/device")
                .header("Authorization", "Basic {base64("+codedAuthString+")}")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("client_id={" + clientId +"}")
                .asString();

        System.out.println(response.getBody());

    }

I'll try my best here hehe. Looks like your Basic authentication it's wrong, try this:

String codedAuthString = clientId + ":" + clientSecret;
String authValueBase64 = new String(Base64.encodeBase64(
                    codedAuthString.getBytes()));
HttpResponse response = Unirest.post("https://allegro.pl.allegrosandbox.pl/auth/oauth/device")
.header("Authorization", "Basic " + authValueBase64 )
.header("Content-Type", "application/x-www-form-urlencoded")
.body("client_id={" + clientId +"}")
.asString();

Let me know if this helps you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM