【问题标题】:Java OAuth 2.0 get access tokenJava OAuth 2.0 获取访问令牌
【发布时间】:2024-07-15 15:55:01
【问题描述】:

我想通过 Java 代码从 REST API 获取 access token OAuth 2.0,问题是我已经成功地使用 Bash 脚本(curl 命令)

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

使用该代码 sn-p 我得到了以下响应:

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

当我尝试使用 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());

回复是:

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

经过几次研究和尝试,我仍然不知道我的 Java 代码请求中缺少什么。有人可以帮我添加缺少的东西或指导我正确的方向吗?

CollabNet 文档:

萨索

【问题讨论】:

  • 您的 Java 代码使用的是 JSON 正文,但 bash 脚本直接在 post 请求中包含参数,而不是在 JSON 正文中。你试过用同样的方式称呼它吗?
  • @JPinzon01 你的意思是在 URL 中创建一个带有参数的 POST 请求?示例:POST:www.myapi.com?grant_type=password&client_id=api-client&scope=$scope&username=$username&password=$password
  • 不在 URL 中,而是在正文中。您可以尝试使用与 bash 脚本相同的字符串而不是 JSON。问题是 Oauth2 服务器不期望 JSON 请求,而是期望正文中带有 HTTP 参数的常规 POST。响应是 JSON 对象,但请求不必是相同的格式。
  • 感谢您的评论,但我按照您的建议进行了尝试,现在仍然有效。错误消息 "{"error_description":"Invalid request","error":"invalid_request"}"

标签: java rest curl oauth-2.0 collabnet


【解决方案1】:

请尝试:

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();

还有一个关于授权类型的问题你确定吗?
grant_type = client_credentials也许你需要这样的东西。

【讨论】: