簡體   English   中英

Android OAuth Retrofit訪問令牌請求

[英]Android OAuth Retrofit Access Token Request

任何人都可以告訴確切的格式將下面的代碼轉換為改造

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

應使用基本身份驗證對客戶端憑據進行身份 即帶標題

Authorization: Basic base64encode(clientId:clientSecret)

其中base64encode(clientId:clientSecret)是實際的BASE64編碼的字符串clientId:clientSecret 因此,要更新您的界面,它可能看起來更像

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。 以上內容已經過測試,也適用於您。

使用OkHttp攔截器,這變得更容易。

Interceptor interceptor = chain -> {
        Request original = chain.request();
        Request request = original.newBuilder()
                .header("Authorization", Credentials.basic(CLIENT_ID, CLIENT_SECRET))
                .method(original.method(), original.body())
                .build();
        return chain.proceed(request);
    };

OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

return new Retrofit.Builder()
                .baseUrl(baseURL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Credentials.basic方法將基於64編碼您的客戶端ID和客戶端密鑰。 然后將攔截器連接到OkHttpClient客戶端並添加到Retrofit對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM