简体   繁体   English

Web 应用程序部署不生成授权令牌

[英]Web application deployed not generating authorization tokens

I'm trying send using gmail api with oauth2 credentials like below我正在尝试使用 gmail api 和 oauth2 凭据发送,如下所示

private Credential getCredentials(NetHttpTransport httpTransport) throws IOException {
        // Load client secrets.
        try {
            Resource file = resourceLoader.getResource("classpath:credentials.json");
            InputStream inputStream = file.getInputStream();
            GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
                    new InputStreamReader(inputStream));
            // Build flow and trigger user authorization request.
            GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, JSON_FACTORY,
                    clientSecrets, SCOPES)
                            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
                            .setAccessType("offline").build();

            return new AuthorizationCodeInstalledApp(flow,  new LocalServerReceiver()).authorize("user");
        } catch (Exception exception) {
            exception.printStackTrace();
            LOGGER.info("Exception occured:: {}", exception.getMessage());
            throw new RecordNotFoundException(exception.getMessage());
        }

    }

using desktop app's credentials.json file.使用桌面应用程序的 credentials.json 文件。

When I have deployed in dev server I am unable to generate access and refresh token saved file.当我在开发服务器中部署时,我无法生成访问和刷新令牌保存的文件。

Could you please help me.请你帮助我好吗。

AuthorizationCodeInstalledApp OAuth 2.0 authorization code flow for an installed Java application that persists end-user credentials. AuthorizationCodeInstalledApp OAuth 2.0 授权代码流,用于保留最终用户凭据的已安装 Java 应用程序。

You cant deploy that to a server its going to open the authorization window on the server.您不能将其部署到服务器上,它会在服务器上打开授权 window。

For a web application it looks like you should be following this Oauth对于 web 应用程序,看起来您应该关注此Oauth

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
  }
}

From what I have understood from your question and comments you want to achieve the following:根据我从您的问题和评论中了解到的情况,您希望实现以下目标:

With your current code send email messages from your application which already works on your local machine and now you want to do it too in a web server.使用您当前的代码从您的应用程序发送 email 消息,这些消息已经在您的本地计算机上运行,现在您也想在 web 服务器中执行此操作。

Considering that you are the only user that needs to authorise the application you can achieve what you are aiming using service accounts .考虑到您是唯一需要授权应用程序的用户,您可以使用服务帐户实现您的目标。

A service account works best for applications like yours where you don't need authorization from your users but rather from your account to for example send emails automatically.服务帐户最适合像您这样的应用程序,您不需要用户授权,而是需要您的帐户授权,例如自动发送电子邮件。

These type of accounts belong to your application rather than to an individual user and can make API requests without the need to authorise through the UI.这些类型的帐户属于您的应用程序而不是单个用户,并且可以发出 API 请求,而无需通过 UI 授权。 This guide from the documentation will walk you step through step on how to set up your authorization with service accounts. 文档中的本指南将引导您逐步了解如何使用服务帐户设置授权。

Moreover, bare in mind that in order for the service account to execute requests in your name (as you need an user to send emails) you should use domain-wide authorization so that the service account can make such requests in the name of the user.此外,请记住,为了让服务帐户以您的名义执行请求(因为您需要用户发送电子邮件),您应该使用域范围的授权,以便服务帐户可以以用户的名义发出此类请求. Also note that you need a Google Workspace account to implement domain wide authorization (let me know if you don't have it as I can propose a workaround) .另请注意,您需要一个 Google Workspace 帐户来实施域范围的授权(如果您没有,请告诉我,因为我可以提出解决方法)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM