需求如图:我们需要使用golang调用一个获取token的http接口,并返回token
其中:
- 关键字grant_type为字符串“password”
- 关键字username为分配的用户名
- 关键字password为分配的密码,需进行AES的CBC加密,填充方式为:ZEROS_PADDING
- 关键字Authorization为头内容
具体实现代码如下:
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
var (
timeOut int
addr string
userName string
passWord string
clientId string
clientSecret string
//cache config
token string
//token_type string
)
type AesCrypt struct {
Key []byte
Iv []byte
}
type iAuthorize interface {
SetAuthorizeConfig(url, name, passwd, id, secret string, timeout int) int
Authorize() int
}
//加密
func (a *AesCrypt) Encrypt(data []byte) ([]byte, error) {
aesBlockEncrypt, err := aes.NewCipher(a.Key)
if err != nil {
println(err.Error())
return nil, err
}
content := pKCS5Padding(data, aesBlockEncrypt.BlockSize())
cipherBytes := make([]byte, len(content))
aesEncrypt := cipher.NewCBCEncrypter(aesBlockEncrypt, a.Iv)
aesEncrypt.CryptBlocks(cipherBytes, content)
return cipherBytes, nil
}
//解密
func (a *AesCrypt) Decrypt(src []byte) (data []byte, err error) {
decrypted := make([]byte, len(src))
var aesBlockDecrypt cipher.Block
aesBlockDecrypt, err = aes.NewCipher(a.Key)
if err != nil {
println(err.Error())
return nil, err
}
aesDecrypt := cipher.NewCBCDecrypter(aesBlockDecrypt, a.Iv)
aesDecrypt.CryptBlocks(decrypted, src)
return pKCS5Trimming(decrypted), nil
}
func pKCS5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func pKCS5Trimming(encrypt []byte) []byte {
padding := encrypt[len(encrypt)-1]
return encrypt[:len(encrypt)-int(padding)]
}
func SetAuthorizeConfig(url, name, passwd, id, secret string, timeout int) int{
addr = url
userName = name
passWord = passwd
clientId = id
clientSecret = secret
timeOut = timeout
return Authorize()
}
func Authorize() int {
urlValues := url.Values{}
urlValues.Add("grant_type","password")
urlValues.Add("username", userName)
var aesCrypt = AesCrypt{
Key: []byte("imccpzx,qwertyui"),
Iv: []byte("imccpzx,qwertyui"),
}
var text = passWord
result, err := aesCrypt.Encrypt([]byte(text))
if err != nil {
fmt.Println(err)
}
pass64 := base64.StdEncoding.EncodeToString(result)
fmt.Println(pass64)
urlValues.Add("password", pass64)
header := clientId + ":" + clientSecret
ustrAuthorization := "Basic " + base64.StdEncoding.EncodeToString([]byte(header))
//jsonStr, _ := json.Marshal(urlValues)
myUrl, err := url.Parse(addr)
if err != nil {
fmt.Println(err.Error())
}
myUrl.Path = "/securiry/imccp-security/oauth/token"
httpUrl := myUrl.Query()
httpUrl.Add("grant_type", "password")
httpUrl.Add("username", userName)
httpUrl.Add("password", pass64)
myUrl.RawQuery = httpUrl.Encode()
client := &http.Client{}
req,_ := http.NewRequest("POST",myUrl.String(),nil)
req.Header.Add("Authorization",ustrAuthorization)
resp,_ := client.Do(req)
if resp.StatusCode == 200 {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
} else {
fmt.Printf("the errorcode is: %d\n, the staus is: %s\n", resp.StatusCode, resp.Status)
}
return 0
}
func main(){
SetAuthorizeConfig("http://gateway.xx.cn", "ygy2019", "12345", "gbnl", "gbgla34asd41sdf1", 10)
}
效果如图: