我要为我的应用创建一个 OAuth2.0 的登录系统,一切正常,直到过期令牌!
对于本节我写了这个方法:
public static String getAccessToken(){
String accessToken;
if(!UserSession.getInstance().isExpired()){
return UserSession.getInstance().getUserAuthAccessToken();
} else {
PostRequests.getFreshToken(new ResultListener<String>() {
@Override
public void getResult(String result, boolean error) {
if(error){
} else {
Authorization authorization = gson.fromJson(result, Authorization.class);
UserSession.getInstance().setUserAuthorizationInfo(authorization.AccessToken, authorization.TokenType, authorization.Expiration, authorization.RefreshToken, authorization.Scope);
accessToken = authorization.AccessToken;
}
}
});
}
}
正如您所看到的,如果未过期,我会在我的app共享首选项中返回访问令牌存储,但如果过期,我会刷新请求(Volley + Gson),以使其新鲜。
但我无法从内部阶级到达accessToken
:(
如何从此方法返回String?
答案 0 :(得分:1)
使用侦听器是解决此问题的一种方法。
public interface ITokenListener {
void onTokenObtained(String accessToken);
}
public void usingGetAccessTokenMethod() {
getAccessToken(new ITokenListener() {
@Override
public void onTokenObtained(String accessToken) {
//use accessToken
}
});
}
public void getAccessToken(final ITokenListener listener){
if(!UserSession.getInstance().isExpired()){
listener.onTokenObtained(UserSession.getInstance().getUserAuthAccessToken());
} else {
PostRequests.getFreshToken(new ResultListener<String>() {
@Override
public void getResult(String result, boolean error) {
if(error){
} else {
Authorization authorization = gson.fromJson(result, Authorization.class);
UserSession.getInstance().setUserAuthorizationInfo(authorization.AccessToken, authorization.TokenType, authorization.Expiration, authorization.RefreshToken, authorization.Scope);
listener.onTokenObtained(UserSession.getInstance().getUserAuthAccessToken());
}
}
});
}
}