You*_*ton 1 redirect android oauth2 retrofit2 okhttp3
我试图为Android应用程序制作oauth2。它几乎没有错误。
我的错误是重定向时没有授权之类的标题
MyCookieCode。当我登录时,它将发送授权。但是当我重定向时不起作用
public static Retrofit getLoginRetrofitOnAuthz() {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl(ServerValue.AuthServerUrl).addConverterFactory(GsonConverterFactory.create());
if (LoginRetrofitAuthz == null) {
httpClientAuthz.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
String str = etUsername.getText().toString() + ":" + etPassword.getText().toString();
String Base64Str = "Basic " + Base64.encodeToString(str.getBytes(), Base64.NO_WRAP);
System.out.println(Base64Str);
Request request = chain.request().newBuilder().addHeader("Authorization", Base64Str).build();
return chain.proceed(request);
}
});
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
httpClientAuthz.cookieJar(new JavaNetCookieJar(cookieManager));
LoginRetrofitAuthz = builder.client(httpClientAuthz.build()).build();
}
return LoginRetrofitAuthz;
}
Run Code Online (Sandbox Code Playgroud)
您知道如何在重定向中保留标头吗?
小智 5
实际上,罪人是OkHttp,但不是Retrofit。OkHttp故意删除所有身份验证标头:
// When redirecting across hosts, drop all authentication headers. This
// is potentially annoying to the application layer since they have no
// way to retain them.
if (!sameConnection(url)) {
requestBuilder.removeHeader("Authorization");
}
Run Code Online (Sandbox Code Playgroud)
这是此问题的讨论:https : //github.com/square/retrofit/issues/977
您可以使用OkHttp身份验证器。如果返回401错误,它将被调用。因此,您可以使用它来重新验证请求。
httpClient.authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
return response.request().newBuilder()
.header("Authorization", "Token " + DataManager.getInstance().getPreferencesManager().getAuthToken())
.build();
}
});
Run Code Online (Sandbox Code Playgroud)
但是在我的情况下,服务器返回403 Forbidden而不是401。而且我必须
response.headers().get("Location");
就地创建并触发另一个网络请求:
public Call<Response> getMoreBills(@Header("Authorization") String authorization, @Url String nextPage)