HTTP摘要身份验证在PHP [英] HTTP Digest authenticating in PHP

查看:172
本文介绍了HTTP摘要身份验证在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证到使用HTTP Digest授权在PHP脚本另一个站点。

I want to authenticate to another site using HTTP Digest authorization in PHP script.

我的函数作为参数只是在 WWW验证头的内容,我想生成正确的响应(授权头)。我发现,解释如何实现这个其他方式(浏览器验证到我的脚本)的例子很多,但并不是这样。我缺少的功能,能够解析WWW-Authenticate头内容的生成反应。是否有实现这个标准的一些功能或公共库?

My function has as parameter just content of the WWW-Authenticate header and I want to generate correct response (Authorization header). I have found many examples that explain how to implement this the other way (browser authenticate to my script) but not this way. I am missing function that is able to parse WWW-Authenticate header content a generate response. Is there some standard function or common library that implements this?

推荐答案

好吧,没有答案,我已经调查蟒蛇就是骗在这里,它重写PHP执行。这是最简单可行的一块code的。仅支持 MD5 散列,但对我的作品:

Ok, no answer yet, I have investigated python implementation that lied around here and rewrite it to PHP. It is the simplest possible piece of code. Supports only md5 hashing, but works for me:

function H($param) {
    return md5($param);
}
function KD($a,$b) {
    return H("$a:$b");
}
function parseHttpDigest($digest) {
    $data = array();
    $parts = explode(", ", $digest);

    foreach ($parts as $element) {
    	$bits = explode("=", $element);
    	$data[$bits[0]] = str_replace('"','', $bits[1]);
    }
    return $data;
}

function response($wwwauth, $user, $pass, $httpmethod, $uri) {        
        list($dummy_digest, $value) = split(' ', $wwwauth, 2);    
        $x = parseHttpDigest($value);
        $realm = $x['realm'];        
        $A1 = $user.":".$realm.":".$pass;        
        $A2 = $httpmethod.":".$uri;

        if ($x['qop'] == 'auth') {
            $cnonce = time();
            $ncvalue = 1;
            $noncebit = $x['nonce'].":".$ncvalue.":".$cnonce.":auth:".H($A2);
            $respdig = KD(H($A1), $noncebit);
        }else {
            # FIX: handle error here
        }

        $base  = 'Digest username="'.$user.'", realm="';
        $base .= $x['realm'].'", nonce="'.$x['nonce'].'",';
        $base .= ' uri="'.$uri.'", cnonce="'.$cnonce;
        $base .= '", nc="'.$ncvalue.'", response="'.$respdig.'", qop="auth"';
        return $base;
    }

用法:

# TEST
$www_header = 'Digest realm="TEST", nonce="356f2dbb8ce08174009d53c6f02c401f", algorithm="MD5", qop="auth"';
print response($www_header, "user", "password", "POST", "/my_url_query");

这篇关于HTTP摘要身份验证在PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆