Adv*_*Dog 6 authentication android retrofit2
我正在尝试使用Retrofit(2.0.0-beta3),但是当使用Authenticator添加令牌时,我似乎无法从同步调用中获取数据.我们在后端的日志记录只显示了很多登录尝试,但我无法从正文中获取实际添加到标题的数据.
public static class TokenAuthenticator implements Authenticator {
@Override
public Request authenticate(Route route, Response response) throws IOException {
// Refresh your access_token using a synchronous api request
UserService userService = createService(UserService.class);
Call<Session> call = userService.emailLogin(new Credentials("handle", "pass"));
// This call is made correctly, as it shows up on the back-end.
Session body = call.execute().body();
// This line is never hit.
Logger.d("Session token: " + body.token);
// Add new header to rejected request and retry it
return response.request().newBuilder()
.header("Auth-Token", body.token)
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
我不太确定为什么它甚至不打印任何东西.有关如何解决此问题的任何提示将非常感谢,感谢您抽出宝贵时间提供帮助.
这些是我一直在阅读的有关如何实施Retrofit的资料.
使用Authenticator:
使用Retrofit 2进行同步调用:
我设法使用TokenAuthenticator和拦截器获得了一个不错的解决方案,并认为我会分享这个想法,因为它可能会帮助其他人.
添加处理向标头添加令牌的'TokenInterceptor'类是令牌存在,而'TokenAuthenticator'类在没有令牌时处理这种情况,我们需要生成一个令牌.
我确信有更好的方法可以实现这一点,但我认为这是一个很好的起点.
public static class TokenAuthenticator implements Authenticator {
@Override
public Request authenticate( Route route, Response response) throws IOException {
...
Session body = call.execute().body();
Logger.d("Session token: " + body.token);
// Storing the token somewhere.
session.token = body.token;
...
}
private static class TokenInterceptor implements Interceptor {
@Override
public Response intercept( Chain chain ) throws IOException {
Request originalRequest = chain.request();
// Nothing to add to intercepted request if:
// a) Authorization value is empty because user is not logged in yet
// b) There is already a header with updated Authorization value
if (authorizationTokenIsEmpty() || alreadyHasAuthorizationHeader(originalRequest)) {
return chain.proceed(originalRequest);
}
// Add authorization header with updated authorization value to intercepted request
Request authorisedRequest = originalRequest.newBuilder()
.header("Auth-Token", session.token )
.build();
return chain.proceed(authorisedRequest);
}
}
Run Code Online (Sandbox Code Playgroud)
资源:
http://lgvalle.xyz/2015/07/27/okhttp-authentication/
小智 5
我有类似的身份验证器,它适用于2.0.0-beta2.
如果您从Authenticator获得了大量登录尝试,我建议您确保在进行同步调用时,您没有使用Authenticator进行该调用.如果您的"emailLogin"失败,那可能会循环结束.
另外我建议添加loggingInterceptor以查看所有到服务器的流量:使用Retrofit 2进行记录
归档时间: |
|
查看次数: |
13983 次 |
最近记录: |