最近用golang 和python对接接口,由于之前验证那块没有设置好,然后又为了进度,最近决定用http自带的basic 验证,
php的代码很快就验证通过了
/** * @param $url * @param $filename * @param $path * @param $type 上传代码 */ private function upload_file($url,$path){ $data = array( 'avatar'=>new \CURLFile(realpath($path)) ); $ch = curl_init(); //设置帐号和帐号名 curl_setopt($ch, CURLOPT_USERPWD, 'xxx:xxxx' ); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_getinfo($ch); $return_data = curl_exec($ch); curl_close($ch); return $return_data; }
python由于用的是2.7的版本,代码如下
# -*- coding: utf-8 -*- import urllib2 # Create an OpenerDirector with support for Basic HTTP Authentication... auth_handler = urllib2.HTTPBasicAuthHandler() auth_handler.add_password(realm='PDQ Application', uri='http://localhost:8080/v1/xxx/index', user='xxx', passwd='xxxx') opener = urllib2.build_opener(auth_handler) 以下是正确的请求方式 #import requests #req = requests.post('http://localhost:8080/v1/xxxx/index', auth=('xxxx', 'xxxx'),params={"lists":[{"1212"}]}) #print(req.text)
golang 这边的验证大概代码如下,用的是beego框架;然后写上一个filter的中间键自已实现的验证,弄死都读不到Authorization,
package middleware import ( "encoding/base64" "github.com/astaxie/beego/context" "github.com/astaxie/beego" ) const( HeaderAuthorization = "Authorization" basic = "Basic" ) func Author(ctx *context.Context) bool { auth := ctx.Input.Header(HeaderAuthorization) l := len(basic) if len(auth) > l+1 && auth[:l] == basic { b, err := base64.StdEncoding.DecodeString(auth[l+1:]) if err != nil { return false } cred := string(b) for i := 0; i < len(cred); i++ { if cred[i] == ':' { // Verify credentials return validator(cred[:i], cred[i+1:]) } } } return false } func validator(user string ,pass string) bool { if user == beego.AppConfig.String("auth::appkey") && pass == beego.AppConfig.String("auth::appsecret"){ return true } return false }
后面还是强大的http://stackoverflow.com/questions/21936332/idiomatic-way-of-requiring-http-basic-auth-in-go 这个上面找到了答案
func main() { // atcd := dispatcher.NewAtcDispatcher(4) // atcd.Run() if beego.BConfig.RunMode == "dev" { beego.BConfig.WebConfig.DirectoryIndex = true beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" //} else { //权限检查 var FilterAuth = func(ctx *context.Context) { if !middleware.Author(ctx) { ctx.ResponseWriter.Header().Set("WWW-Authenticate", `Basic realm="MY REALM"`) ctx.ResponseWriter.WriteHeader(401) ctx.ResponseWriter.Write([]byte("{\"ResultCode\": 401,\"ResultMsg\": \"你没有权限\"}\n")) } } beego.InsertFilter("/v1/*", beego.BeforeStatic, FilterAuth) } beego.Run() }
然后就可以通过:curl http://xxx:xxx@127.0.0.1:8080/v1/xx/12 这样访问就没有问题了
golang requiring HTTP Basic Auth