我认为我的问题的背景很清楚,但我想指出我使用OAuth进行Web应用程序,所以我使用了Google提供的这个示例:OAuth 2.0 for WebApplication 我知道我必须创建(例如在同一个类中(由HttpServlet扩展))一个doGet方法(显然在Override中)来获取正确的流来授权用户拥有自己的范围,所以像这样:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//This is a class to obtain the Current Google User's ID
UserService userService = UserServiceFactory.getUserService();
String userId = userService.getCurrentUser().getUserId();
String url = getAuthorizationUrl(userId);
if(req.getParameter("code")!=null){
try {
String authorizationCode = req.getParameter("code");
getCredentials(authorizationCode);
} catch (CodeExchangeException | NoRefreshTokenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//the next page (my homePage)
resp.sendRedirect("/home");
}
else{
resp.sendRedirect(url);
}
}
这项成功的工作,如果你看一下提供的方法' getCredential(authorizationCode)'它显示了2个方法:storeCredential和getStoredCredential。 第一种方法工作得很好,我可以在我的数据存储中看到refreshToken和accessToken字符串。 问题是构建getStoredCredential方法,因为它返回一个Credential对象,我不知道写它。我告诉你方法的开头,但我不知道如何继续。
static Credential getStoredCredentials(String googlePlusUserId) {
// TODO: Implement this method to work with your database. Instantiate a new
// Credential instance with stored accessToken and refreshToken.
//These methods of my Class correctly get the tokens (already debugged)
String refreshToken = UserManager.getStoredRefreshToken(googlePlusUserId);
String accessToken = UserManager.getStoredAccessToken(googlePlusUserId);
//How can i continue here? :-( to return Credential with correct parameters?
//......
//......
//......
//......
}
此方法是否永远有效? 因为在Google OAuth Playgroung中有一个复选框,上面写着:"在令牌过期之前自动刷新令牌" (我认为在3600秒内)。所以,我不认为完成我的getStoredCredential让我的应用程序正常工作......我认为这只是为了获取总是最后一个令牌...所以在这种情况下,我永远无法使用存储获取新的accessToken RefreshToken。 有人能帮帮我吗?也许用一个简单的方法刷新旧的AccessToken。