Android OAuth 改造访问令牌请求 [英] Android OAuth Retrofit Access Token Request
问题描述
谁能告诉将以下代码转换为改造的确切格式
Can anyone tell the exact format to convert below code into retrofit
curl -X POST -d "grant_type=password&username=admin&password=admin&scope=read+write" -u"clientId:clientSecret" http://myserver/o/token/
我试过这样的东西,但它不起作用
I have tried something like this but it isn't working
@FormUrlEncoded
@POST("/o/token/")
AccessTokenResponse getToken(@Field("client_id") String client_id, @Field("client_secret") String client_secret,
@Field("grant_type") String grant_type, @Field("username") String username,
@Field("password") String password, @Field("scope") String scope);
推荐答案
客户端凭据应使用 基本身份验证进行身份验证.即带有标题
Client credentials should be authenticated with Basic Authentication. i.e with header
Authorization: Basic base64encode(clientId:clientSecret)
其中 base64encode(clientId:clientSecret)
是 clientId:clientSecret
的实际 base64 编码字符串.因此,要更新您的界面,它可能看起来更像
where base64encode(clientId:clientSecret)
is the actual base64 encoded string of clientId:clientSecret
. So to update your interface it might look something more like
public interface OAuthTokenService {
@POST("/api/token")
@FormUrlEncoded
@Headers({
"Accept: application/json"
})
AccessTokenResponse getAccessToken(@Field("grant_type") String grantType,
@Field("username") String username,
@Field("password") String password,
@Header("Authorization") String authorization);
}
然后设置标题,做类似的事情
Then to set the header, do something like
public class Main {
public static void main(String[] args) {
RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint("http://localhost:8080")
.setConverter(new JacksonConverter())
.build();
OAuthTokenService service = restAdapter.create(OAuthTokenService.class);
byte[] credentials = "clientId:clientSecret".getBytes();
String basicAuth = "Basic " + Base64.getEncoder().encodeToString(credentials);
AccessTokenResponse response = service
.getAccessToken("password", "admin", "admin", basicAuth);
System.out.println(response.getAccessToken());
}
}
注意上面的 java.util.Base64
类使用 Java 8.您可能没有使用 Java 8,在这种情况下,您需要找到不同的编码器.
Note the above uses Java 8 for the java.util.Base64
class. You may not be using Java 8, in which case you will need to find a different encoder.
我也在使用 Jackson 进行转换,只是因为我不使用 Gson.以上已经过测试,应该也适用于您.
I am also using Jackson for conversion, only because I don't use Gson. The above has been tested and should work for you also.
这篇关于Android OAuth 改造访问令牌请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!