使用 REST API 在 Go 中向 Azure 进行身份验证

我正在尝试使用戈朗向 Azure 服务管理/图形 API 进行身份验证。使用纯 REST 接口。无论我做什么,我总是以错误告终:


{"error":"invalid_request","error_description":"AADSTS900144: The request body must contain the following parameter: '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))

}


精慕HU
浏览 277回答 1
1回答

一只甜甜圈

由普拉文·普雷马拉特内发布的微软请求文档显示,请求需要使用OAuth 2.0标准的要求进行格式化。Content-Type: application/x-www-form-urlencoded以下是微软的文档和示例:https://docs.microsoft.com/en-us/graph/auth/auth-concepts#register-your-app-with-the-microsoft-identity-platformPOST /common/oauth2/v2.0/token HTTP/1.1Host: https://login.microsoftonline.comContent-Type: application/x-www-form-urlencodedclient_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 mainimport (    "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)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go