You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用Keycloak获取Token遇405错误:未用GET却提示无GET资源方法

问题:调用Keycloak获取Token时触发405错误(未使用GET却提示GET方法不被允许)

测试微服务时,从Keycloak服务器获取Token,运行Robot Framework关键字时返回错误:"No resource method found for GET, return 405 with Allow header",但代码里明明用的是POST方法。

关键字代码

A valid token for "${client}" with secret "${client_secret}"
    ${auth} =    Create List    ${client}    ${client_secret}
    ${headers_dict} =    Create Dictionary    Content-Type=application/x-www-form-urlencoded    Accept=application/json
    ${data_dict} =    Create Dictionary    grant_type=client_credentials
    Create Session    mysession    http://keycloak.${domain}    auth=${auth}
    ${resp}=    POST On Session    mysession    /auth/realms/gdp/protocol/openid-connect/token    headers=${headers_dict}    data=${data_dict}
    Should Be Equal As Strings    ${resp.status_code}    200
    ${token}=    catenate    Bearer    ${resp.json()}[access_token]
    Set Suite Variable    ${EX_TOKEN}    ${token}
    Log    ${EX_TOKEN}

日志内容

15:34:24.123 INFO POST On Session mysession /auth/realms/gdp/protocol/openid-connect/token
15:34:24.456 ERROR RequestsLibrary.PostOnSession Request failed with status 405
15:34:24.456 DEBUG Response content: {"error":"Method Not Allowed","error_description":"No resource method found for GET, return 405 with Allow header"}
15:34:24.457 FAIL Should Be Equal As Strings 405 200

解决思路与方案

1. 排查重定向导致的方法转换

Keycloak的Token端点如果接收到的请求路径存在问题(比如末尾多了斜杠、路径前缀错误),会触发301/302重定向,而HTTP规范中,POST请求被重定向后默认会转为GET请求,这就会出现你看到的405错误。

  • 检查请求路径:如果你的Keycloak版本是17+(Quarkus版本),端点路径已经去掉了/auth前缀,正确路径应为/realms/gdp/protocol/openid-connect/token,旧路径会触发重定向。
  • 确认路径末尾没有多余斜杠,比如/token/会被重定向到/token,进而转换请求方法。

2. 修正Client认证方式

你的代码中用Create Session的auth参数传递了client和secret,这会自动添加HTTP Basic认证头,但Keycloak的client_credentials模式下,你需要确保:

  • 要么在请求体中传递client_id和client_secret,去掉Session的auth参数:
    ${data_dict} =    Create Dictionary    grant_type=client_credentials    client_id=${client}    client_secret=${client_secret}
    Create Session    mysession    http://keycloak.${domain}
    
  • 要么保留Basic认证,但需在Keycloak控制台中配置该Client:
    • 确保Client的"Access Type"为confidential;
    • 开启"Service Accounts Enabled";
    • 确认"Authentication Flow Overrides"中允许client_credentials流程。

3. 抓包验证实际请求

用工具(如Wireshark、Charles)抓包确认实际发送的请求方法、路径和参数,看是否存在意外的重定向或请求方法被篡改的情况,这能快速定位问题根源。

内容的提问来源于stack exchange,提问作者Slashlinux

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 10:31:22