在Go中通过REST API对Azure进行身份验证
时间:2024-02-22
浏览:219
作者:佚名
大家好,今天本人给大家带来文章《在Go中通过REST API对Azure进行身份验证》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!
问题内容
我正在尝试使用 golang 对 azure 服务管理/图形 api 进行身份验证。 使用纯粹的 rest api。 无论我做什么,我总是会遇到错误:
{"error":"invalid_request","error_description":"aadsts900144: 请求正文必须包含以下参数:'grant_type'.
由于我没有使用 sdk,因此可用的示例有限。任何帮助将不胜感激。
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
func main() {
authendpoint := "https://login.microsoftonline.com/8xxxxx7-6372-4bcb-xxx-xxxxxx/oauth2/token"
jsonData := []byte(`{
"resource": "https://graph.microsoft.com",
"client_id": "xxxxxxxx-7549-4ea2-b00d-xxxxxxxxxxx",
"client_secret": "Q.xxxxxxxxxxxxxx-6_CgA4yOi_8sS-",
"grant_type": "client_credentials",
}`)
request, err := http.NewRequest("POST", authendpoint, bytes.NewBuffer(jsonData))
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
log.Fatal(err)
}
body, err := ioutil.ReadAll(resp.Body)
var res map[string]interface{}
json.NewDecoder(resp.Body).Decode(&res)
log.Println(string(body))
}正确答案
Praveen Premaratne 发布的 microsoft 请求文档显示该请求需要使用 content-type: application/x-www-form-urlencoded 进行格式化,这是 OAuth 2.0 standard 的要求。
以下是 microsoft 文档和示例:
post /common/oauth2/v2.0/token http/1.1 host: https://login.microsoftonline.com content-type: application/x-www-form-urlencoded client_id=6731de76-14a6-49ae-97bc-6eba6914391e &scope=user.read%20mail.read &code=oaaabaaaail9kn2z27uubvwfpbm0glwqjvzcte9ukp3psx1axxujq3n8b2jrlk4oxvxr... &redirect_uri=http%3a%2f%2flocalhost%2fmyapp%2f &grant_type=authorization_code &client_secret=jqqx2pno9bpm0ueihupzyrh
以下是实现此目的的方法:
package main
import (
"fmt"
"net/http"
"net/url"
"strings"
)
func main() {
authendpoint := "https://login.microsoftonline.com/8xxxxx7-6372-4bcb-xxx-xxxxxx/oauth2/token"
body := url.Values(map[string][]string{
"resource": {"https://graph.microsoft.com"},
"client_id": {"xxxxxxxx-7549-4ea2-b00d-xxxxxxxxxxx"},
"client_secret": {"Q.xxxxxxxxxxxxxx-6_CgA4yOi_8sS-"},
"grant_type": {"client_credentials"}})
request, err := http.NewRequest(
http.MethodPost,
authendpoint,
strings.NewReader(body.Encode()))
if err != nil {
panic(err)
}
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
panic(err)
}
fmt.Println(resp.StatusCode)
}
对我来说,当我从请求正文中删除资源并将范围添加为正文中的新参数时,它就起作用了。
今天关于《在Go中通过REST API对Azure进行身份验证》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
