golang 請求帶驗證信息的坑


最近用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 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM