HTTP状态-401未经授权

时间:2020-04-28 10:45:23

标签: spring rest api oauth-2.0

我试图从curl转换为Java代码,目的是调用API创建令牌,但得到401响应。

卷曲代码:

curl -X POST \
  https://apigw.dev/commercial/oauth/create-token \
  -H 'Content-Type: application/x-www-form-urlencoded' \
  -d 'client_id=dfdfdfdfd&client_secret=dfdfdf&grant_type=client_credentials'

这是我的Java代码:

@RestController
public class TokenController {

    @RequestMapping(value = "/getAccessToken", method = RequestMethod.POST)
    public ClientCredentialsResourceDetails getAccessToken(ClientCredentialsResourceDetails resource) throws Exception {

        resource.setAccessTokenUri(tokenUri);
        resource.setClientId(clientId);
        resource.setClientSecret(clientSecret);
        resource.setGrantType("client_credentials");
        resource.setClientAuthenticationScheme(AuthenticationScheme.header);
        resource.setScope(Arrays.asList("read", "write"));

        System.out.println(resource);

        return resource;
    }
}

,这里是结果:

    "timestamp": "2020-04-28T14:02:28.381+0000",
    "status": 401,
    "error": "Unauthorized",
    "message": "Unauthorized",
    "path": "/getAccessToken"
}

非常感谢您的建议,谢谢。

1 个答案:

答案 0 :(得分:0)

您正在使用CURL发出POST请求,但您的rest控制器已配置为GET。我猜您有另一个使用POST方法的/ getAccessToken端点,该端点需要令牌。 同样,默认情况下,reason: DeadlineExceeded类中的每个方法都会消耗@RestController并产生一个application/json。 如果您的请求是application/json,则将请求的消费类型更改为Content-Type: application/x-www-form-urlencoded