Spring 带有球衣请求的 OAuth 2.0:输入正确凭据后响应 401 未经授权

Spring OAuth 2.0 with jersey request : response 401 Unauthorized after entering correct credentials

这是我的问题:当我尝试调用此方法时,出现此错误

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 encoded and used for 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));