简体   繁体   English

Java OAuth 2.0 获取访问令牌

[英]Java OAuth 2.0 get access token

I want to get access token OAuth 2.0 from REST API via Java code, the thing is that I've managed to successfully get it back from the server with Bash script (curl command)我想通过Java代码从 REST API 获取访问令牌 OAuth 2.0 ,问题是我已经成功地使用Bash脚本(curl 命令)从服务器取回了它

Bash script (working): Bash 脚本(工作):

#!/usr/bin/env bash

       # Base URL of TeamForge site.
       site_url="https://teamforge.example.com"

       # TeamForge authentication credentials.
       username="foo"
       password="bar"

       # Requested scope (all)
       scope="urn:ctf:services:ctf

       curl -d "grant_type=password&client_id=api-client&scope=$scope&username=$username&password=$password" $site_url/sf/auth/token

With that code snippet I'got this response:使用该代码片段,我得到了以下回复:

  {
         "access_token": "eyJraWQiOiIxIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiJhZG1pbiIsImF1ZCI...",
         "token_type": "Bearer"
       }

When I've tried to translate it to Java code using Unirest :当我尝试使用Unirest将其转换为Java代码

  HttpResponse<JsonNode> jsonResponse = Unirest.post("\"https://teamforge.example.com/sf/auth/token")
                .header("accept", "application/json")
                .body("{\"grant_type\":\"password\"," +
                        "\"client_id\":\"api-client\", " +
                        "\"scope\":\"urn:ctf:services:ctf\"," +
                        "\"username\":\"foo\"," +
                        "\"password\":\"bar\"}")

                .asJson();

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

Response was:回应是:

{"error_description":"Invalid grant","error":"invalid_grant"}

After a couple of researches and tries, I still don't know what am I missing in my Java code request.经过几次研究和尝试,我仍然不知道我的 Java 代码请求中缺少什么。 Can someone help me to add missing stuff or guide me to right directions?有人可以帮我添加缺少的东西或指导我正确的方向吗?

CollabNet docs: CollabNet 文档:

Saso佐佐

Please try:请尝试:

JsonNode jsonResponse = Unirest.post("https://teamforge.example.com/sf/auth/token")
.header("Content-Type", "application/json")
.field("scope", "urn:ctf:services:ctf")
.field("client_id", "api-client")
.field("grant_type", "password")
.field("username", "foo")
.field("password", "bar")
.asJson()
.getBody();

And one more question are you sure about grant type ?还有一个问题你确定是关于授权类型吗?
grant_type = client_credentials maybe you need something like this. grant_type = client_credentials也许你需要这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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