如何在空手道中生成 auth 2.0 我在空手道演示项目中看到了一个示例,但在我们的例子中,我们需要将其作为“授权代码”发送

问题描述 投票:0回答:4

如何通过空手道生成 OAuth 2.0 令牌。

我们如何在 Postman 中进行尝试:

  1. 在“授权”选项卡上选择 OAuth 2.0
  2. 选择标头前缀承载
  3. Grant-Type 为“授权码”
  4. 选择回调 URL,因为当我们单击“提交”时,它会重定向到浏览器,我们必须在其中输入凭据,并且验证用户后,浏览器将重定向回 Postman
  5. 添加“身份验证 URL”和“访问令牌 URL”
  6. 输入“客户端ID”和“客户端密码”
  7. 选择“客户端身份验证”作为“作为基本身份验证标头发送”。

Postman 然后重定向到浏览器,我们在其中输入用户名和密码,经过身份验证后,它会将用户重定向回带有访问令牌的邮递员。

问题: 当我们在空手道中提供 grant_type 作为“授权代码”时,我们会收到一个错误,如

{"error":"unsupported_grant_type","error_description":"Unsupported grant_type"}
。这里要提供什么,当我们提供“密码”时,我们会得到 401,当我们提供“授权码”时,我们会得到 400。

其次,我们是否可以自动化这样的场景:浏览器也被调用,我们必须输入凭据,我们可以通过空手道来实现它,然后我们必须存储令牌并传入 API?

  Background:
    * url 'http://localhost:8080/pathdetails'

  Scenario: get all users and then get the first user by id
    * path 'token'
    * form field grant_type = 'authorization code'
    * form field client_id = 'ourapiclient'
    * form field client_secret = '324243324-3334-334-343-3432423424'
    * method post
    * status 200

    * def accessToken = response.access_token

已编辑************

我现在尝试向 Auth URL 发送 API 请求,该请求会重定向到浏览器并返回 HTML 页面。

    Given url 'http://localhost:8080/myurlpath/auth'
    * form field response_type = 'code'
    * form field client_id = 'abcc'
    * form field scope = 'openconnect'
    * form field redirect_uri = 'http://localhost:8080/redirecturlpath'
    * form field state = 'cEY3R-YfsoM9232diS72COdHTA8uPv9K49pjZaPag5M.8akinzwobn8.abcd4'
    * method get
    * status 200
    * print 'Response is........',response

这返回了一个 HTML 页面,该页面与我从 Postman 发送请求时看到的页面完全相同。现在如何在此 html 页面上输入空手道中的用户名和密码,因为此页面是作为上述 API 响应的一部分返回的。

我期望上面会返回一个代码,之后我将调用请求令牌端点,但上面将我重定向到输入用户名和密码的位置,然后一旦成功,它会重定向回 Postman,在 URL 中我可以看到代码还有。

curl --request POST \
  --url 'https://YOUR_DOMAIN/oauth/token' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data grant_type=authorization_code \
  --data 'client_id=YOUR_CLIENT_ID' \
  --data client_secret=YOUR_CLIENT_SECRET \
  --data code=YOUR_AUTHORIZATION_CODE \
  --data 'redirect_uri=https://YOUR_APP/callback'

如何获取token API所需的code?

我尝试发送 Auth API 进行访问,如下所示,但响应中没有返回代码或令牌。

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'
* fullscreen()
And input('#username', 'username')
And input('#password', 'password')
When click('#login')

上面的内容不会返回任何错误,但它也不会返回我正在寻找的代码

karate
4个回答
2
投票

@Maddy 要查看授权类型,您需要访问 auth0,或者要求您的开发人员告诉您此处实施了哪些授权,您可以阅读更多信息: https://auth0.com/docs/configure/applications/application-grant-types

在这里您可以阅读如何实现授权代码流程: https://auth0.com/docs/login/authentication/add-login-auth-code-flow

为了让您的生活更轻松,您可以要求开发人员实施Password-realm-grant,但不建议这样做。


0
投票

以下是如何纠正 oAuth 2.0 令牌生成之一

* def cid = 'client_id'
* def csec = 'token_secret'
* def AuthCode = Java.type('com.test.qa.aut.authCode')  
* print AuthCode.Code()  
* def authentication = 'Basic ' + AuthCode.Code(cid, csec)
* print authentication

* url 'https://acpint.online.com/default/np/oauth2/'
* header Authorization = authentication
And header Content-Type = 'application/x-www-form-urlencoded; charset=utf-8'
* form field grant_type = 'client_credentials'
Then method post
And status 200
Then print response

Java 类:

package com.test.qa.aut;
import java.util.Base64;
public class authCode {
    public static String Code(String clientId, String clientSecret) {
        String auth = clientId + ":" + clientSecret;
        String authentication = Base64.getEncoder().encodeToString(auth.getBytes());
        return authentication;
    }
}

0
投票

这是我使用 PKCE 创建访问令牌 OAuth 2.0 的解决方案

    Feature: OAuth 2.0 Authentication with Authorization Code grant type and PKCE

  Background:
    * url 'https://aaa.amazoncognito.com/oauth2'
    * def scope = 'openid profile'
    * def callbackURL = 'https://aaa.com'
    * def grantType = 'authorization_code'
    * configure ssl = true
    * def ac = Java.type('utilities.AuthCode')
    * def newClass = new ac()
    * def cV = newClass.generateCodeVerifier()
    #* print 'code verify= '+ cV
    * def cC = newClass.generateCodeChallenge(cV)
    #* print 'code chal= '+ cC
    * def sleep = function(millis){ java.lang.Thread.sleep(millis) }
    * def delay = 1000


  Scenario: Get Access Token with PKCE

    Given path 'authorize'
    * configure followRedirects = false
    * form field response_type = 'code'
    * form field client_id = clientID
    * form field client_secret = clientSecret
    * form field scope = 'openid profile'
    * form field redirect_uri = 'https://aaa.com'
    * form field code_challenge = cC
    * form field code_challenge_method = 'S256'
    * method get
    * status 302
    * def location = responseHeaders['Location'][0]

    #auth code
    * configure driver = { type: 'chrome', addOptions: ["--remote-allow-origins=*"] }
    Given driver location
    * sleep(delay)
    And input('/html/body/div[1]/div/div[2]/div[2]/div[2]/div[2]/div/div/form/div[1]/input', username)
    And input('/html/body/div[1]/div/div[2]/div[2]/div[2]/div[2]/div/div/form/div[2]/input', password)
    When click('/html/body/div[1]/div/div[2]/div[2]/div[2]/div[2]/div/div/form/input[3]')
    * def actualUrl = waitForUrl('?code')
    * def authCode = actualUrl.substring(actualUrl.lastIndexOf('=') + 1)
    * driver.quit()

    #final
    * configure followRedirects = true
    Given url 'https://aaa.amazoncognito.com/oauth2/token'
    * header Content-Type = 'application/x-www-form-urlencoded'
    * form field grant_type = 'authorization_code'
    * form field client_id = clientID
    * form field client_secret = clientSecret
    * form field code_verifier = cV
    * form field code = authCode
    * form field redirect_uri = 'https://aaa.com'
    * method post
    * status 200
    * match response.token_type == 'Bearer'
    * def id_token = response.id_token
    * def access_token = response.access_token
    * def refresh_token = response.refresh_token
    #* print 'access token is = '+ access_token

对于 AuthCode java 类是

    package utilities;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

public class AuthCode {




    /**
     * This method generates a secure string used as the PKCE code verifier value.
     * In PKCE, you use the code verifier value:
     * 1. When you generate a code challenge value.
     * 2. When you exchange an authorization code for a bearer JWT token.
     * @return A random code verifier value.
     */
    final public String generateCodeVerifier() {

        SecureRandom secureRandom = new SecureRandom();
        byte[] bytes = new byte[36];
        secureRandom.nextBytes(bytes);

        String result = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
        //System.out.println("code verifier = " + result);
        return result;
    }


    /**
     * This method generates a code challenge value by SHA-256 and base64 encoding the code verifier value.
     * In PKCE, you use the code challenge value when you construct the authorization request uri.
     * @param codeVerifierValue A random string value.
     * @return An encoded code challenge string value.
     * @throws NoSuchAlgorithmException
     */
    public String generateCodeChallengeHash(String codeVerifierValue) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte[] codeVerifierBytes = codeVerifierValue.getBytes(StandardCharsets.US_ASCII);
        byte[] digest = messageDigest.digest(codeVerifierBytes);

        return Base64.getUrlEncoder().withoutPadding().encodeToString(digest);
    }

   public String generateCodeChallenge(String cV){


      // System.out.println("code verifier in cC method = " + cV);
       String result;
       try {
           result = generateCodeChallengeHash(cV);
       } catch (NoSuchAlgorithmException e) {
           throw new RuntimeException(e);
       }

      //System.out.println("generated Code Challenge = " + result);
       return result;
   }

}

0
投票

我正在尝试你的代码,但它不起作用,你能帮忙吗

© www.soinside.com 2019 - 2024. All rights reserved.