将 HTTP Basic-Auth 与 Google App Engine URLFetch 服务结合使用

发布于 2024-08-03 13:33:25 字数 434 浏览 6 评论 0 原文

如何指定用户名和密码以使用 App Engine 的 URLFetch 服务(Java 中)?

看来我可以设置 HTTP 标头:

URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-MyApp-Version", "2.7.3");        

Basic-Auth 的适当标头是什么?

How can I specify the username and password for making Basic-Auth requests with App Engine's URLFetch service (in Java)?

It seems I can set HTTP headers:

URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-MyApp-Version", "2.7.3");        

What are the appropriate headers for Basic-Auth?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

转角预定愛 2024-08-10 13:33:25

这是 http 上的基本身份验证标头:

授权:基本 base64 编码(用户名:密码)

例如:

GET /private/index.html HTTP/1.0
Host: myhost.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

您需要执行以下操作:

URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization",
"Basic "+codec.encodeBase64String(("username:password").getBytes());

为此,您需要获得一个 base64 编解码器 api,例如 Apache Commons 编解码器

This is a basic auth header over http:

Authorization: Basic base64 encoded(username:password)

eg:

GET /private/index.html HTTP/1.0
Host: myhost.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

You will need to do this:

URL url = new URL("http://www.example.com/comment");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization",
"Basic "+codec.encodeBase64String(("username:password").getBytes());

And to do that you will want to get a base64 codec api, like the Apache Commons Codec

翻身的咸鱼 2024-08-10 13:33:25

对于那些有兴趣在 Python 中执行此操作的人(就像我一样),代码如下所示:

result = urlfetch.fetch("http://www.example.com/comment",
                        headers={"Authorization": 
                                 "Basic %s" % base64.b64encode("username:pass")})

For those interested in doing this in Python (as I was), the code looks like this:

result = urlfetch.fetch("http://www.example.com/comment",
                        headers={"Authorization": 
                                 "Basic %s" % base64.b64encode("username:pass")})
海的爱人是光 2024-08-10 13:33:25

您在调用 openConnection() 之前设置了一个身份验证器,如下所示,

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
});

由于只有一个全局默认身份验证器,因此当您有多个用户在多个线程中执行 URLFetch 时,这并不能很好地工作。如果是这样的话,我会使用 Apache HttpClient。

编辑:我错了。 App Engine 不允许使用身份验证器。即使允许,我们也会遇到全局身份验证器实例的多线程问题。即使您无法创建线程,您的请求仍可能在不同的线程中得到服务。所以我们只需使用此函数手动添加标头,

import com.google.appengine.repackaged.com.google.common.util.Base64;
    /**
     * Preemptively set the Authorization header to use Basic Auth.
     * @param connection The HTTP connection
     * @param username Username
     * @param password Password
     */
    public static void setBasicAuth(HttpURLConnection connection,
            String username, String password) {
        StringBuilder buf = new StringBuilder(username);
        buf.append(':');
        buf.append(password);
        byte[] bytes = null;
        try {
            bytes = buf.toString().getBytes("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            assert false;
        }

        String header = "Basic " + Base64.encode(bytes);
        connection.setRequestProperty("Authorization", header);
    }

You set up an Authenticator before you call openConnection() like this,

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
});

Since there is only one global default authenticator, this doesn't really work well when you have multiple users doing the URLFetch in multiple threads. I would use Apache HttpClient if that's the case.

EDIT: I was wrong. App Engine doesn't allow Authenticator. Even if it's allowed, we would have the multi-thread issue with a global authenticator instance. Even though you can't create threads, your requests may still get served in different threads. So we just add the header manually using this function,

import com.google.appengine.repackaged.com.google.common.util.Base64;
    /**
     * Preemptively set the Authorization header to use Basic Auth.
     * @param connection The HTTP connection
     * @param username Username
     * @param password Password
     */
    public static void setBasicAuth(HttpURLConnection connection,
            String username, String password) {
        StringBuilder buf = new StringBuilder(username);
        buf.append(':');
        buf.append(password);
        byte[] bytes = null;
        try {
            bytes = buf.toString().getBytes("ISO-8859-1");
        } catch (java.io.UnsupportedEncodingException uee) {
            assert false;
        }

        String header = "Basic " + Base64.encode(bytes);
        connection.setRequestProperty("Authorization", header);
    }
戏剧牡丹亭 2024-08-10 13:33:25

使用 HttpURLConnection 给了我一些问题(由于某种原因,我尝试连接的服务器不接受身份验证凭据),最后我意识到使用 GAE 的低级 URLFetch 实际上要容易得多API (com.google.appengine.api.urlfetch) 如下所示:

URL fetchurl = new URL(url);

String nameAndPassword = credentials.get("name")+":"+credentials.get("password");
String authorizationString = "Basic " + Base64.encode(nameAndPassword.getBytes());

HTTPRequest request = new HTTPRequest(fetchurl);
request.addHeader(new HTTPHeader("Authorization", authorizationString));

HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
System.out.println(new String(response.getContent()));

这有效。

Using HttpURLConnection gave me some problems (for some reason the server I was trying to connect to didn't accept auth credentials), and finally I realized that it's actually much easier to do using GAE's low-level URLFetch API (com.google.appengine.api.urlfetch) like so:

URL fetchurl = new URL(url);

String nameAndPassword = credentials.get("name")+":"+credentials.get("password");
String authorizationString = "Basic " + Base64.encode(nameAndPassword.getBytes());

HTTPRequest request = new HTTPRequest(fetchurl);
request.addHeader(new HTTPHeader("Authorization", authorizationString));

HTTPResponse response = URLFetchServiceFactory.getURLFetchService().fetch(request);
System.out.println(new String(response.getContent()));

This worked.

貪欢 2024-08-10 13:33:25

请注意第一个答案:setRequestProperty 应获取不带冒号的属性名称(“授权”而不是“授权:”)。

Note on the first answer: setRequestProperty should get the property name without the colon ("Authorization" rather than "Authorization:").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文