如何在java中访问摘要式身份验证

时间:2013-11-19 01:13:16

标签: java rest glassfish digest-authentication challenge-response

总是打印出相同的信息..我的错是什么?

结果消息[responseCode:401,responseMessage:Unauthorized]

// http request1

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.connect();

// http response1 401并进行回复

    NtrHashtable authorizationParameters = identifyAuthorization(con);

    String md1 = username + ":" + authorizationParameters.get("realm") + ":" + password;
    md5.update(md1.getBytes());
    String digestedMd1 = digest32HexDigits(md5.digest());

    String md2 = "POST" + ":" + path;
    md5.update(md2.getBytes());
    String digestedMd2 = digest32HexDigits(md5.digest());

    byte[] tmpCnonce = new byte[16];
    SecureRandom rand;
    rand = SecureRandom.getInstance("SHA1PRNG");
    rand.nextBytes(tmpCnonce);
    String cnonce = rand.getSeed(1024).toString();

    String tmpResponse = digestedMd1 + ":" + 
    authorizationParameters.get("nonce") + ":" +
         "00000001" + ":" +
         cnonce + ":" +
         authorizationParameters.get("qop") + ":" +
         digestedMd2;
    md5.update(tmpResponse.getBytes());
    String response = digest32HexDigits(md5.digest());  

//构建对摘要挑战的响应

    String authorizationRequest = authorizationParameters.get("schema") + " " + 
              "username=\"" + username + "\", " +
              "realm=\"" + authorizationParameters.get("realm") + "\", " +
              "nonce=\"" + authorizationParameters.get("nonce") + "\", " +
              "uri=\"" + path + "\", " +
              "qop=\"" + authorizationParameters.get("qop") + "\", " +
              "cnonce=\"" + cnonce + "\", " +
              "nc=" + "00000001" + ", " +
              "response=\"" + response + "\", " +
              "opaque=\"" + authorizationParameters.get("opaque") + "\"";

// http request2 authorization header

    con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("authorization", authorizationRequest);

// digest32HexDigits

    private static String digest32HexDigits(byte[] digest) {
        StringBuffer digestString = new StringBuffer();
        int low, hi ;

        for(int i=0; i < digest.length; i++) {
           low = (digest[i] & 0x0f);
           hi = ((digest[i] & 0xf0)>>4);
           digestString.append(Integer.toString(hi, 16));
           digestString.append(Integer.toString(low, 16));
        }
        return digestString.toString();
     }

//的System.out.println(authorizationRequest);

授权:摘要用户名=“changeit”,realm =“changeit”,nonce =“1384790250915:6792652dc7defc4bb2a8dd35cc5a5fd974b2b2a4002448e17310507e63ba682c”,uri =“/ changeit / changeit /”,qop =“auth”,cnonce =“[B @ 1dc80063” ,nc = 00000001,response =“2bf3f7b58a0de6cc844456044e0f820f”,opaque =“53C20D789CFC51F65C0250C790A2F130”

我不知道..我的错在哪里..

0 个答案:

没有答案