2015-05-09 49 views
4

谁能告诉确切的格式如下代码转换成改造安卓改造的OAuth访问令牌请求

curl -X POST -d "grant_type=password&username=admin&password=admin&scope=read+write" -u"clientId:clientSecret" http://myserver/o/token/ 

我已经试过这样的事情,但它不工作

@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); 
+0

401未经授权的错误正在提出! –

+0

身份验证错误:无法应对任何这些挑战 401未经授权的错误正在提出! –

+0

改装1或改装2? –

回答

5

客户端证书应通过Basic Authentication认证。即与头

Authorization: Basic base64encode(clientId:clientSecret) 

其中base64encode(clientId:clientSecret)是编码的clientId:clientSecret串的实际的base64。因此,更新您的界面可能看起来更像

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

然后设置标题,这样做

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 8为java.util.Base64类。您可能没有使用Java 8,在这种情况下,您需要找到不同的编码器。

我也在使用Jackson进行转换,只是因为我没有使用Gson。以上已经过测试,应该也适合你。

+0

“AccessTokenResponse”是什么类型的对象? –

+1

@IgorGanapolsky它的组成。它应该具有响应中的所有属性。它只是一个POJO,就像你会处理任何其他的JSON响应一样。 –

+0

谢谢,这个解决方案的作品 – Rinav