You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
74 lines
2.0 KiB
74 lines
2.0 KiB
package service |
|
|
|
import ( |
|
"encoding/base64" |
|
"encoding/json" |
|
"errors" |
|
"fmt" |
|
"io/ioutil" |
|
"net/http" |
|
"net/url" |
|
) |
|
|
|
type DemoConfig struct { |
|
ClientSecret string |
|
ClientId string |
|
TokenUrl string |
|
RootUrlOrder string |
|
AccessToken string |
|
} |
|
|
|
func GetDefaultConfig() *DemoConfig { |
|
var demoConfig DemoConfig |
|
// TODO: (clientId, clientSecret, tokenUrl)请使用实际值替换 |
|
// App secret, 在AppGallery Connect创建应用之后,系统自动分配的公钥 |
|
demoConfig.ClientSecret = "524921589d516c7216951aa389c030681923cd22dfc4477871f9306430eefb6d" |
|
// client id指的是您的APP ID |
|
// App ID, 在AppGallery Connect创建应用之后,系统自动分配的唯一标识符 |
|
demoConfig.ClientId = "112487401" |
|
// 用于获取authorization token的url,具体请参见基于OAuth 2.0开放鉴权 |
|
demoConfig.TokenUrl = "https://oauth-login.cloud.huawei.com/oauth2/v3/token" |
|
|
|
return &demoConfig |
|
} |
|
|
|
type AtResponse struct { |
|
AccessToken string `json:"access_token"` |
|
} |
|
|
|
type AtClient struct { |
|
} |
|
|
|
var AtDemo = &AtClient{} |
|
|
|
func (atDemo *AtClient) GetAppAt() (string, error) { |
|
demoConfig := GetDefaultConfig() |
|
urlValue := url.Values{"grant_type": {"client_credentials"}, "client_secret": {demoConfig.ClientSecret}, "client_id": {demoConfig.ClientId}} |
|
resp, err := http.PostForm(demoConfig.TokenUrl, urlValue) |
|
if err != nil { |
|
return "", err |
|
} |
|
defer resp.Body.Close() |
|
bodyBytes, err := ioutil.ReadAll(resp.Body) |
|
if err != nil { |
|
return "", err |
|
} |
|
var atResponse AtResponse |
|
json.Unmarshal(bodyBytes, &atResponse) |
|
if atResponse.AccessToken != "" { |
|
return atResponse.AccessToken, nil |
|
} else { |
|
return "", errors.New("Get token fail, " + string(bodyBytes)) |
|
} |
|
} |
|
|
|
func BuildAuthorization() (string, error) { |
|
appAt, err := AtDemo.GetAppAt() |
|
if err != nil { |
|
return "", err |
|
} |
|
oriString := fmt.Sprintf("APPAT:%s", appAt) |
|
var authString = base64.StdEncoding.EncodeToString([]byte(oriString)) |
|
var authHeaderString = fmt.Sprintf("Basic %s", authString) |
|
return authHeaderString, nil |
|
}
|
|
|