如何使用groovy-wslite调用Microsoft Graph REST API

ao218c7q  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(175)

我正在尝试使用Java库在groovy脚本上调用Microsoft Graph API。然而,即使部分成功,我在当前项目中使用它时仍存在一些严重问题,因此我考虑尝试使用groovy-wslite调用REST API。
这是我目前获得访问令牌的代码:

def authorizeHost = "https://login.microsoftonline.com"
def authorizePath = "/${azureSetting.getTenantID()}/oauth2/v2.0/authorize?"
try {
    RESTClient client = new RESTClient(authorizeHost)
    def params = [
            "client_id":azureSetting.getClientID(),
            "scope": "https://graph.microsoft.com/.default",
            "response_type": "code"
        ]
    def response = client.post(
        path: authorizePath,
    )
    {
        type ContentType.JSON
        json    params

    }
    LOGGER.info("Success: " + (response.statusCode == 200));
    LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    LOGGER.info("Error: " + sw.toString());
}

来自日志的响应:

AADSTS900144: The request body must contain the following parameter: 'client_id'.

我如何更改上面的代码,以便Microsoft Graph REST API能够识别我发送的内容并发送回访问令牌。
UPDATE:经过尝试,我发现body os post方法应该如下所示:

type "application/x-www-form-urlencoded"
urlenc client_id: azureSetting.getClientID(), 
    scope: "https://graph.microsoft.com/.default", 
    response_type: "code"
cyej8jka

cyej8jka1#

根据文档https://learn.microsoft.com/en-us/graph/auth-v2-user#token-request,您的请求应包含Content-Type: application/x-www-form-urlencoded
您正在尝试发送json
这是您的代码,但指向测试的httpbin.org服务器,它可以显示您发送到服务器的确切内容
有一个小变化:ContentType.JSON -〉ContentType.URLENC

@Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.3', transitive=false)

import wslite.rest.*
//just for test
def azureSetting = [ getClientID:{-> "12345"} ]
def LOGGER = [info:{x-> println x}]
//redefined host and url
def authorizeHost = "HTTP://httpbin.org"
def authorizePath = "/post"

try {
    RESTClient client = new RESTClient(authorizeHost)
    def params = [
            "client_id":azureSetting.getClientID(),
            "scope": "https://graph.microsoft.com/.default",
            "response_type": "code"
        ]
    def response = client.post(
        path: authorizePath,
    )
    {
        type ContentType.URLENC // <-- THE ONLY CHANGE IN YOUR CODE
        json    params

    }
    LOGGER.info("Success: " + (response.statusCode == 200));
    LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    LOGGER.info("Error: " + sw.toString());
}

相关问题