如何将 dropbox 的身份验证令牌直接获取到 java 程序中,以便用户无需复制粘贴它



我正在开发一个应用程序,我必须从保管箱帐户上传文件和下载文件,应用程序是一个java桌面应用程序。我已经使用了示例代码,并且能够毫无故障地运行它。但是我想绕过用户需要将身份验证代码表单浏览器复制到应用程序,如何做到这一点。我希望我的应用程序将身份验证令牌直接获取到应用程序中,因为这会导致用户开销。所有专家请帮助我。这是我实现的代码。

import com.dropbox.core.*;
import java.awt.Desktop;
import java.io.*;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws IOException, DbxException {
    // Get your app key and secret from the Dropbox developers website.
    final String APP_KEY = "xxxxxxxxxxxxxxxx";
    final String APP_SECRET = "xxxxxxxxxxxxxxxx";
    DbxAppInfo appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);
    DbxRequestConfig config = new DbxRequestConfig("JavaTutorial/1.0",
        Locale.getDefault().toString());
    DbxWebAuthNoRedirect webAuth = new DbxWebAuthNoRedirect(config, appInfo);
    // Have the user sign in and authorize your app.
    String authorizeUrl = webAuth.start();
    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.");
    Desktop.getDesktop().browse(java.net.URI.create(authorizeUrl));
    String code = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
    // This will fail if the user enters an invalid authorization code.
    DbxAuthFinish authFinish = webAuth.finish(code);
    DbxClient client = new DbxClient(config, authFinish.accessToken);
    System.out.println("Linked account: " + client.getAccountInfo().displayName);
    File inputFile = new File("OpenCv_Video_display_link.txt");
    FileInputStream inputStream = new FileInputStream(inputFile);
    try {
        DbxEntry.File uploadedFile = client.uploadFile("/OpenCv_Video_display_link.txt",
            DbxWriteMode.add(), inputFile.length(), inputStream);
        System.out.println("Uploaded: " + uploadedFile.toString());
    } finally {
        inputStream.close();
    }
    DbxEntry.WithChildren listing = client.getMetadataWithChildren("/");
    System.out.println("Files in the root path:");
    for (DbxEntry child : listing.children) {
        System.out.println("    " + child.name + ": " + child.toString());
    }
    FileOutputStream outputStream = new FileOutputStream("121verbs.pdf");
    try {
        DbxEntry.File downloadedFile = client.getFile("/121verbs.pdf", null,
            outputStream);
        System.out.println("Metadata: " + downloadedFile.toString());
    } finally {
        outputStream.close();
    }
}
}
  1. 转到 https://www.dropbox.com/developers/apps
  2. 点击应用程序。在此页面上的 Outh 2 下,查找"生成的访问令牌"。
  3. 单击生成。
  4. 这是访问令牌。这将验证用户是您,并且您不必每次都通过标准授权流。

我已经注释了不必要的代码,您只需要最后一行。

/* // Have the user sign in and authorize your app.
String authorizeUrl = webAuth.start();
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.");
String code = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
// This will fail if the user enters an invalid authorization code.
DbxAuthFinish authFinish = webAuth.finish(code); */
String accessToken = "Your access token goes here";

基于Dropbox博客中的此示例,我在java中制作了此示例,它将打开一个Web视图,您可以在其中引入Dropbox凭据,然后dropbox将重定向您并且重定向URL将具有令牌,然后我们从URl获取令牌并打印到控制台。

    public class AnotherClass extends Application {
    public static void main(String[] args) {
        java.net.CookieHandler.setDefault(new com.sun.webkit.network.CookieManager());
        launch(args);
    }
    //This can be any URL. But you have to register in your dropbox app
    final String redirectUri = "https://www.dropbox.com/1/oauth2/redirect_receiver";
    final String AppKey = "YOUR APP KEY ";
    final String url = "https://www.dropbox.com/1/oauth2/authorize?client_id=" + AppKey + "&response_type=token&redirect_uri=" + redirectUri;

    @Override
    public void start(Stage pStage) throws Exception {
        Stage primaryStage = pStage;
        primaryStage.setTitle("Dropbox Sign In");

        WebView webView = new WebView();
        WebEngine webEngine = webView.getEngine();
        webEngine.load(url);
        webEngine.locationProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> arg0, String oldLocation, String newLocation) {
                try {
                    if (newLocation.startsWith(redirectUri)) {
                        ArrayMap<String, String> map = parseQuery(newLocation.split("#")[1]);
                        if (map.containsKey("access_token")) {
                            System.out.print("Token: " + map.get("access_token"));
                        }
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
        StackPane stackPane = new StackPane();
        stackPane.getChildren().add(webView);
        Scene rootScene = new Scene(stackPane);
        primaryStage.setScene(rootScene);
        primaryStage.show();
    }
    ArrayMap<String, String> parseQuery(String query) throws UnsupportedEncodingException {
        ArrayMap<String, String> params = new ArrayMap<String, String>();
        for (String param : query.split("&")) {
            String[] pair = param.split("=");
            String key = URLDecoder.decode(pair[0], "UTF-8");
            String value = URLDecoder.decode(pair[1], "UTF-8");
            params.put(key, value);
        }
        return params;
    }
}

根据我在 Android 平台上的开发经验,你可以插入 JavaScript 代码扫描网页并提取身份验证代码,如下所示:

@Override
public void onPageFinished(final WebView webView, final String url) {
    if (AUTHORIZE_SUBMIT_URL.equalsIgnoreCase(url)
            && AUTHORIZE_SUBMIT_TITLE.equalsIgnoreCase(webView.getTitle())) {
        webView.loadUrl("javascript:HtmlViewer.showHTML"
                + "('<html>'+document.getElementById('auth-code').innerHTML+'</html>');");
    }
}

最新更新