トップ 履歴 一覧 カテゴリ ソース 検索 ヘルプ RSS ログイン

ScrapCode/Java/HttpAuth

INDEX

HTTP認証

HttpURLConnection による接続で、Basic認証 および Digest認証を行う。

Authenticator を継承したクラスを作成し、ユーザ認証が要求されたときにユーザ情報( PasswordAuthentication )を返すようにする。ユーザ認証の要求時にユーザに入力させる場合は、Authenticator#getPasswordAuthentication() でダイアログなどを表示する。URLConnection で対象サーバに接続する前に Authenticator#setDefault() で作成した Authenticator をセットしておく。

しかし、まぁ、なんでこんな作りなんだろうか? Authenticator#setDefault が static メソッドなので、マルチスレッド環境でサーバやページによって認証情報を変えたい場合とかどうするんでしょう…。あと、失敗時のリトライ回数を指定できないのだろうか…。

HTTPユーザー認証処理

デフォルトコンストラクタでユーザ情報を指定して認証処理を行うようにする。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.net.Authenticator;
import java.net.PasswordAuthentication;

/**
 * HTTPユーザー認証処理クラス.
 */
public class HttpAuthenticator extends Authenticator {

    /** ユーザ名 */
    private final String username;
    /** パスワード */
    private final String password;

    /**
     * 指定されたユーザ情報でHTTPユーザー認証処理オブジェクトを構築します。
     * @param username ユーザ名
     * @param password パスワード
     */
    public HttpAuthenticator(String username, String password) {
        if (username == null || password == null)
            throw new IllegalArgumentException("username or password is null.");

        this.username = username;
        this.password = password;
    }

    /**
     * 認証に使用するユーザ名を取得します。
     * @return ユーザ名
     */
    public String getUsername() {
        return this.username;
    }

    /**
     * 認証に使用するパスワードを取得します。
     * @return パスワード
     */
    public String getPassword() {
        return this.password;
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        //System.out.println("RequestingHost\t:" + getRequestingHost());
        //System.out.println("RequestingSite\t:" + getRequestingSite());
        //System.out.println("RequestingPort\t:" + getRequestingPort());
        //System.out.println("RequestingProtocol\t:" + getRequestingProtocol());
        //System.out.println("RequestingPrompt\t:" + getRequestingPrompt());
        //System.out.println("RequestingScheme\t:" + getRequestingScheme());
        //System.out.println("RequestingURL\t:" + getRequestingURL());
        //System.out.println("RequestorType\t:" + getRequestorType());
        //System.out.println("UserName/PassWord\t:" + this.username + "/" + this.password);
        return new PasswordAuthentication(this.username, this.password.toCharArray());
    }

}

HTTPユーザー認証

// URLとID/PW
URL url = url = new URL("http://wwww.example.com/httpauth/secret.html");
String username = "hoge";
String password = "fuga";

// ユーザ認証情報の設定
HttpAuthenticator httpAuth = new HttpAuthenticator(username, password);
Authenticator.setDefault(httpAuth);

// 認証必要ページへ接続
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.connect();

System.out.println();
System.out.println("Response: " + conn.getResponseCode() + " " + conn.getResponseMessage());

認証処理は20回リトライされる。それでも失敗する場合は、“401 Authorization Required”となる(JDK 1.5, 1.6)

参考

最終更新時間:2010年09月02日 17時19分10秒 指摘や意見などあればSandBoxのBBSへ。