Search code examples
javaapirestlet

Adding an authentication token to header in Restlet


I am trying to make an API call using Restlet in java however when I run my code I get an org.restlet.resource.ResourceException: Unauthorized (401) - The request requires user authentication

The format for the API call is as follows for shell: curl "<api_url>" \ -H "Authorization: Bearer <api_token_here>"

However I am unsure how to add this authorization header in Restlet, as you are not able to add the header using .getRequest().getHeaders().add();

Additionally I have tried to set a challenge response however this also does not appear to work.

        API = new ClientResource(RequestURL);
        API.setProtocol(Protocol.HTTPS);

        ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.CUSTOM);
        AuthHeader.setRawValue("Authorization: Bearer " + APIKey);

        API.getRequest().setChallengeResponse(AuthHeader);

        API.get();

Solution

  • I appear to have solved the issue with the following code:

        ChallengeResponse AuthHeader = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER); 
        AuthHeader.setRawValue(APIKey);
        AuthHeader.setIdentifier("Bearer");
        API.setChallengeResponse(AuthHeader);