【问题标题】:java DropBox SDK generate token with Redirectjava DropBox SDK使用重定向生成令牌
【发布时间】:2020-08-01 01:27:09
【问题描述】:

在阅读了 Dropbox 官方文档后,我设法编写了这段代码来使用 DropBox 对用户进行身份验证并获取他的访问令牌。用户必须复制和粘贴令牌,我不喜欢这一步,我注意到一些开发人员可以使用DbxWebAuth 类的withRedirect() 方法。 有一个使用重定向的示例,但它适用于 Web 应用程序,我无法将其调整为我的桌面应用程序。你们中有人与此有关吗? 这是目前我的代码

 public static void main(String[] args) throws Exception {

    String accessToken = "";
    String userLocale = null;
    DbxRequestConfig requestConfig = new DbxRequestConfig("text-edit/0.1", userLocale);
    DbxAppInfo appInfo = new DbxAppInfo("myString", "myString");
    DbxWebAuth auth = new DbxWebAuth(requestConfig, appInfo);
    DbxWebAuth.Request requestAuth = DbxWebAuth.newRequestBuilder().withNoRedirect().build();
    String authorizeUrl = auth.authorize(requestAuth);

    System.out.println("1. Go to " + authorizeUrl);
    System.out.println("2. Click \"Allow\" (you might have to log in first).");
    System.out.println("3. Copy the authorization code.");

    //Abrimos el enlace de autenticación del paciente en la carpeta de DropBox
    try {
        URL authenticationURL = new URL(authorizeUrl);
        Desktop.getDesktop().browse(authenticationURL.toURI());

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    JFrame frame1 = new JFrame("InputDialog Example #2");
    frame1.setAlwaysOnTop(true);

    String code = JOptionPane.showInputDialog(frame1, "Insert verification code");

    System.out.println(code);
    code = code.trim();

    try {
        DbxAuthFinish authFinish = auth.finishFromCode(code);

        accessToken = authFinish.getAccessToken();

    } catch (Exception e) {

    }
}

【问题讨论】:

    标签: java token dropbox


    【解决方案1】:

    我很懒,这里没有写任何代码,而是在一个回调方案中,您向身份验证服务器提供重定向 URL,该 URL 由您的系统浏览器通过 301 重定向加载,这意味着 Dropbox 服务器不会t 实际上需要访问您的回调 URL,他们所做的只是重定向您的客户端。因此,很多时候人们在测试 Web 应用程序时使用 localhost 作为他们的回调 URL。

    这意味着您实际上不需要运行 Web 服务器来接收在回调 URL 中传递的参数(即您的访问令牌),因为您已经拥有 URL 及其查询参数,提供给您在来自服务器的 301 响应中。尽管有一些小型网络服务器(例如 nanohttpd)很容易嵌入到您的代码中,以防这一切听起来有点过于复杂。

    在代码中嵌入 Web 服务器以侦听回调的替代方法:

    方法一:像你这种情况,如果你不想设置web服务器监听某个端口,那么你的native应用就needs to claim some URL space,这样系统就不会在native中加载了浏览器,而是将 URL 传递给您的本机应用程序。如果这将是一个 Windows 应用程序,您可以register a custom protocol 以拦截使用您的应用程序向该端点发出的请求。您也可以在 iOS 和 Android 上执行此操作。

    方法 2:我的选择 另一种方法是使用 Unirest 或 httpclient 等客户端与 Dropbox 身份验证服务器进行初始联系,而不是像在 try 块中那样使用桌面浏览器更多。这将允许您从 Dropbox 服务器获取响应并对其进行解析。但是,如果您绝对需要访问 Dropbox 网页让用户输入他们的凭据(即您无法确定如何通过 httpclient 传递凭据),那么您可能会卡在使用系统浏览器并使用方法 1。

    Here's an example of making a request with httpclient, choosing to not follow the 301/302 redirect, and then parsing the redirect location (the URL with your access token) from the headers returned.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多