如何在Karate中实现OAuth 2.0 Authorization Code授权模式获取Token
问题1:grant_type报错解决
你返回unsupported_grant_type错误的核心原因是参数值填写错误,OAuth2 标准授权码模式的grant_type取值为**authorization_code**(是下划线连接,不是空格分隔),你之前写的authorization code不符合规范,所以接口无法识别。
另外授权码模式的令牌接口请求,不能只传grant_type、client_id、client_secret三个参数,必须同时传入你获取到的授权码code、和授权阶段配置一致的redirect_uri两个参数,缺少参数就会返回400错误,和你提供的curl示例要求的参数完全匹配。
问题2:获取授权码code的实现方案
Karate 原生支持浏览器自动化操作,你已经写的驱动登录代码逻辑是正确的,缺失的是登录完成后捕获重定向地址中code参数的步骤,完整实现流程如下:
- 完成登录点击操作后,等待页面跳转到你配置的
redirect_uri地址 - 从浏览器当前地址栏的URL中提取
code参数值 - 用提取到的
code请求令牌接口即可拿到access_token
完整可运行示例代码
Scenario: 获取OAuth2令牌并调用业务接口 # 第一步:浏览器自动登录获取授权码code Given driver 'http://localhost:8080/myurlpath/auth?scope=openconnect&state=cEY3R-YfsoM9232diS72COdHTA8uPv9K49pjZaPag5M.8akinzwobn8.abcd4&response_type=code&client_id=abcc&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fauth%2Fmyurlpath' And input('#username', '替换为实际测试用户名') And input('#password', '替换为实际测试密码') When click('#login') # 等待页面跳转到配置的重定向地址,10000为超时时间,单位毫秒可根据实际情况调整 And waitForUrl('http://localhost:8080/redirecturlpath*', 10000) # 从当前URL中提取code参数 * def currentUrl = driver.url * def code = currentUrl.split('code=')[1].split('&')[0] # 第二步:用授权码请求access_token Given url 'http://localhost:8080/pathdetails/token' * form field grant_type = 'authorization_code' * form field client_id = 'ourapiclient' * form field client_secret = '324243324-3334-334-343-3432423424' * form field code = code * form field redirect_uri = 'http://localhost:8080/redirecturlpath' # 适配Client Authentication为Basic Auth Header的要求 * header Authorization = 'Basic ' + karate.encodeBase64('ourapiclient:324243324-3334-334-343-3432423424') When method post Then status 200 * def accessToken = response.access_token # 第三步:后续业务接口携带token调用 Given url '替换为你的业务接口地址' * header Authorization = 'Bearer ' + accessToken When method get Then status 200
补充说明
如果测试环境可以调整配置,你也可以让后端临时开启密码模式,直接用账号密码请求令牌,不需要走浏览器跳转流程,代码会更简洁。如果登录页有验证码校验,建议测试环境关闭验证码或者配置固定测试验证码绕过。
内容的提问来源于stack exchange,提问作者Maddy
相关产品推荐
相关产品推荐

