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

Thi*_*ilo 27 java google-app-engine basic-authentication

如何使用App Engine的URLFetch服务(Java)指定用于制作Basic-Auth请求的用户名和密码?

我似乎可以设置HTTP标头:

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

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

Zom*_*ies 30

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

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

例如:

GET /private/index.html HTTP/1.0
Host: myhost.com
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Run Code Online (Sandbox Code Playgroud)

你需要这样做:

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

要做到这一点,你将需要一个base64编解码器API,如Apache Commons Codec


Luk*_*ncl 14

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

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


ZZ *_*der 6

在调用openConnection()之前设置一个Authenticator,

Authenticator.setDefault(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password.toCharArray());
    }
});
Run Code Online (Sandbox Code Playgroud)

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

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

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);
    }
Run Code Online (Sandbox Code Playgroud)