在每个请求中都有一个有效的 IdToken 的最佳方法是什么?
我的第一个赌注是 okhttpclient 拦截器,它将令牌添加到每个请求中。但我不知道如何在拦截器中获取有效令牌。
GoogleApiClient 的文档建议silentSignIn(GoogleApiClient)
在每次请求之前调用以获取有效令牌。问题是我无法访问拦截器内当前连接的 googleapiclient。
在每个请求中都有一个有效的 IdToken 的最佳方法是什么?
我的第一个赌注是 okhttpclient 拦截器,它将令牌添加到每个请求中。但我不知道如何在拦截器中获取有效令牌。
GoogleApiClient 的文档建议silentSignIn(GoogleApiClient)
在每次请求之前调用以获取有效令牌。问题是我无法访问拦截器内当前连接的 googleapiclient。
GoogleApiClient 只是帮助您连接到 Auth.GOOGLE_SIGN_IN_API 并且您可以创建多个 GoogleApiClient 只要您正确连接/断开它们。在 Google 的示例中,autoManage 配置为在 FragmentActivity 中使用 GoogleApiClient 时为您保存样板代码。当您需要在非 UI 代码中使用它时,假设您在工作线程上。您可以执行以下操作:
private static final GoogleSignInOptions sGso =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(SERVER_CLIENT_ID)
.requestEmail()
.build();
// In your interceptor code:
GoogleApiClient apiClient = new GoogleApiClient.Builder(mContext)
.addApi(Auth.GOOGLE_SIGN_IN_API, sGso)
.build();
try {
ConnectionResult result = apiClient.blockingConnect();
if (result.isSuccess()) {
GoogleSignInResult googleSignInResult =
Auth.GoogleSignInApi.silentSignIn(apiClient).await();
if (googleSignInResult.isSuccess) {
String idToken = googleSignInResult.getIdToken();
// set to header and pass to your server
}
...
}
} finally {
apiClient.disconnect();
}
我最近遇到了类似的问题,我发现了一个不是很漂亮但可行的解决方案。您可以使用静态变量。
public class SessionData {
private static String sessionId;
public static String getSessionId() {
return sessionId;
}
public static void setSessionId(String sessionId) {
SessionData.sessionId = sessionId;
}
}
然后,您可以设置 IdToken,在您从 Google SDK 获得它之后(例如,在用户登录之后)。
SessionData.setSessionId(yourCurrentToken);
在您声明 Retrofit.Builder 的类中,您应该使用以下导入(如您所说,okhttp 拦截器)。
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
该课程的内容应如下所示。
public class RestClient implements Interceptor {
public RestClient() {
OkHttpClient httpClient = new OkHttpClient();
// add your other interceptors …
// add logging as last interceptor
httpClient.interceptors().add(this); // <-- this adds the header with the sessionId to every request
Retrofit restAdapter = new Retrofit.Builder()
.baseUrl(RestConstants.BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build();
}
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (SessionData.getSessionId() != null) {
Request newRequest = originalRequest.newBuilder()
.header("sessionId", SessionData.getSessionId())
.build();
return chain.proceed(newRequest);
}
return chain.proceed(originalRequest);
}
}