【问题标题】:Google OAuth2 Java API set state in callback/redirect URIGoogle OAuth2 Java API 在回调/重定向 URI 中设置状态
【发布时间】:2022-01-11 07:45:53
【问题描述】:

我想在我的重定向 URI 中设置 state 参数,如 https://developers.google.com/identity/protocols/oauth2/web-server#redirecting 中所述

https://accounts.google.com/o/oauth2/v2/auth?
 scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&
 access_type=offline&
 include_granted_scopes=true&
 response_type=code&
 state=state_parameter_passthrough_value&
 redirect_uri=https%3A//oauth2.example.com/code&
 client_id=client_id

我的代码是根据 Google 的文档https://developers.google.com/api-client-library/java/google-api-java-client/oauth2#web_server_applications

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(), GsonFactory.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
  }
}

如何在重定向 URI 中设置 state

我试过了:

@Override
  protected String getRedirectUri(HttpServletRequest req) throws ServletException, IOException {
    GenericUrl url = new GenericUrl(req.getRequestURL().toString());
    url.setRawPath("/oauth2callback");
    url.set("state", "myspecialname");
    return url.build();
  }

但谷歌告诉我:

Authorization Error
Error 400: invalid_request
Invalid redirect_uri contains reserved response param state

【问题讨论】:

    标签: google-oauth google-oauth-java-client


    【解决方案1】:

    这个答案是覆盖onAuthorization:

    @Override
    protected void onAuthorization(HttpServletRequest req, HttpServletResponse resp,
      AuthorizationCodeRequestUrl authorizationUrl) throws ServletException, IOException {
        authorizationUrl.setState("myspecialstate");
        super.onAuthorization(req, resp, authorizationUrl);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多