将身份验证令牌添加到Restlet中的标头

huangapple go评论58阅读模式
英文:

Adding an authentication token to header in Restlet

问题

以下是您要翻译的内容:

我正在尝试使用Java中的Restlet进行API调用,但当我运行我的代码时,我收到一个org.restlet.resource.ResourceException:未经授权(401)- 该请求需要用户身份验证

API调用的格式如下(对于shell):curl "<api_url>" \ -H "Authorization: Bearer <api_token_here>"

然而,我不确定如何在Restlet中添加此授权标头,因为您无法使用.getRequest().getHeaders().add();来添加标头。

此外,我已经尝试设置挑战响应,但这似乎也不起作用。

        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();
英文:

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 &quot;&lt;api_url&gt;&quot; \
-H &quot;Authorization: Bearer &lt;api_token_here&gt;&quot;

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(&quot;Authorization: Bearer &quot; + APIKey);

        API.getRequest().setChallengeResponse(AuthHeader);

        API.get();

答案1

得分: 0

我似乎已经通过以下代码解决了这个问题:

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

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

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

huangapple
  • 本文由 发表于 2020年10月24日 16:47:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64511575.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定