在我的桌面应用程序中,我已成功获得OAuth2 access_token。
我可以通过添加到http请求标头来成功调用Google API:
Authorization: Bearer ya29.gQHsr_vr9P6nsEi06OKWkqKlvzD...
现在我想从http请求中获取当前用户 - 我该怎么做?我不想实施Google Cloud Endpoints。
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
{
// How do I get the logged in user ?
com.google.appengine.api.users.User googleUser = ?;
return user;
}
答案 0 :(得分:0)
如果我理解你的问题。
获取凭据后,您可以执行以下操作:
/**
* Send a request to the UserInfo API to retrieve the user's information.
*
* @param credentials OAuth 2.0 credentials to authorize the request.
* @return User's information.
* @throws NoUserIdException An error occurred.
*/
static Userinfoplus getUserInfo(Credential credentials)
throws NoUserIdException {
Oauth2 userInfoService = new Oauth2.Builder(
HTTP_TRANSPORT, JSON_FACTORY, credentials)
.setApplicationName(APPLICATION_NAME)
.build();
Userinfoplus userInfo = null;
try {
userInfo = userInfoService.userinfo().get().execute();
} catch (IOException e) {
System.err.println("An error occurred: " + e);
}
if (userInfo != null && userInfo.getId() != null) {
return userInfo;
} else {
throw new NoUserIdException();
}
来源: https://developers.google.com/drive/web/credentials
如果有帮助,请告诉我。
答案 1 :(得分:0)
我认为您需要的内容已经解释为here。来自" OAuth服务提供商和App Engine的轻微修改的代码段"该链接的一部分:
import com.google.appengine.api.users.User;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.oauth.OAuthServiceFailureException;
// ...
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// ...
User user = null;
try {
OAuthService oauth = OAuthServiceFactory.getOAuthService();
user = oauth.getCurrentUser();
} catch (OAuthRequestException e) {
// The consumer made an invalid OAuth request, used an access token that was
// revoked, or did not provide OAuth information.
// ...
}
// Rest of your handler code
}