我正在写一个服务,这将写入数据到不同的谷歌云存储帐户。帐户的所有者应该“注册”我的服务,我将定期将数据写入他们的帐户存储桶中。
我想让“注册”尽可能简单。我仍然在试图理解谷歌的OAuth2。我该如何做到这一点?我想用JAVA以编程方式编写数据
发布于 2016-05-25 02:13:26
它的工作方式是,你的应用程序请求用户的同意,用户告诉谷歌这个同意,谷歌给你代表该用户采取行动的凭证。因为涉及到三方,所以这被称为3条腿的OAuth (3LO)。
下面是这个OAuth流程的概述:https://developers.google.com/identity/protocols/OAuth2WebServer#overview
下面是一个使用Java库构建它的示例:https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#web_server_applications
下面是该示例中的Java代码的重要部分:
public class CalendarServletSample extends AbstractAuthorizationCodeServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// do stuff
}
@Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
GenericUrl url = new GenericUrl(req.getRequestURL().toString());
url.setRawPath("/oauth2callback");
return url.build();
}
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
"[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
DATA_STORE_FACTORY).setAccessType("offline").build();
}
@Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
// return user ID
}
}
public class CalendarServletCallbackSample extends AbstractAuthorizationCodeCallbackServlet {
@Override
protected void onSuccess(HttpServletRequest req, HttpServletResponse resp, Credential credential)
throws ServletException, IOException {
resp.sendRedirect("/");
}
@Override
protected void onError(
HttpServletRequest req, HttpServletResponse resp, AuthorizationCodeResponseUrl errorResponse)
throws ServletException, IOException {
// handle error
}
@Override
protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
GenericUrl url = new GenericUrl(req.getRequestURL().toString());
url.setRawPath("/oauth2callback");
return url.build();
}
@Override
protected AuthorizationCodeFlow initializeFlow() throws IOException {
return new GoogleAuthorizationCodeFlow.Builder(
new NetHttpTransport(), JacksonFactory.getDefaultInstance()
"[[ENTER YOUR CLIENT ID]]", "[[ENTER YOUR CLIENT SECRET]]",
Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(
DATA_STORE_FACTORY).setAccessType("offline").build();
}
@Override
protected String getUserId(HttpServletRequest req) throws ServletException, IOException {
// return user ID
}
}您应该注意到,这段代码是围绕常见的Java "Servlet“模型构建的,它还假设您使用某种数据存储来记住用户的刷新令牌。整个OAuth舞蹈的最终结果是获得一个“刷新令牌”,您可以定期使用它来获得一个临时的“会话令牌”,该令牌可以持续长达一个小时。您需要使用某种类型的数据存储来记住所有这些令牌。
https://stackoverflow.com/questions/37404196
复制相似问题