我试图为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;
}
你知道如何在重定向上保留标题吗?
答案 0 :(得分:4)
// 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");
}
以下是对此问题的讨论: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();
}
});
然而在我的情况下,服务器返回403 Forbidden而不是401.而且我必须得到
response.headers().get("Location");
就地创建并触发另一个网络请求:
public Call<Response> getMoreBills(@Header("Authorization") String authorization, @Url String nextPage)