我的问题是:当我试图调用这个方法时,我遇到了这个错误

InboundJaxrsResponse{
    context=ClientResponse{method=POST,
    uri=http://localhost:9001/oauth/token, status=401,
    reason=Unauthorized}} 
public String getToken() {
    String grant_type ="client_credentials";
    String client_id = "abcd";
    String client_secret = "mpoo";

    Form form = new Form();
    form.param("grant_type",grant_type);
    form.param("client_id",client_id);
    form.param("client_secret",client_secret);
    JerseyClientBuilder jerseyClientBuilder = new JerseyClientBuilder();
    JerseyWebTarget jerseyWebTarget =
            jerseyClientBuilder.build().target("http://localhost:9001/oauth/token");
    Response response = jerseyWebTarget.request().post(Entity.form(form));
    return response.toString();
}

有答案吗?

推荐答案

这不是发送令牌请求的正确方式.看看RFC for client_credentials grant type.请求的正确格式如下:

POST /token HTTP/1.1
Host: server.example.com
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded

grant_type=client_credentials

所以只有grant_type应该是Form身体的一部分.client_idclient_secret应为Base64编码,并用于Basic Authentication:

String credentials = client_id + ":" + client_secret;
String base64 = Base64.getEncoder().encode(credentials.getBytes(StandardCharsets.UTF_8));
Response res = jerseyWebTarget.request()
        .header(HttpHeaders.AUTHORIZATION, "Basic " + base64)
        .post(Entity.form(form));

Java相关问答推荐

Java JAR环境(JRE)是否支持模块?

当一个链表中间有一个循环时,它的松散部分会发生什么?

JPackaged应用程序启动MSI调试,然后启动System. exit()

Jooq外键关系

如何在返回bigint []值的子查询中使用any?

@org.springframework.beans.factory.annotation.Autowired(required=true)-注入点有以下注释:-SpringBoot

所有 case 一起输入时输出错误,而单独放置时输出正确

Spring data JPA/Hibernate根据id获取一个列值

无法了解Java线程所消耗的时间

为什么在maven中,getLast方法不适用于List?

Java流传输一个列表并创建单个对象

按属性值从流中筛选出重复项

匹配一组字符或另一组字符

WebSockets和Spring Boot安全性出现错误401

嘲笑黄瓜中的对象

无泄漏函数的Java DRY

using case default on switch语句返回;预览特征切换中的模式匹配仅在源级别20及以上的情况下可用;

为什么child-pom会创建一个新版本

在不带instanceof或switch的java中记录模式

如何解释泛型类层次 struct 中子类的返回值类型和参数定义?