Go проверка для проверки connect2id выдает ошибку «invalid_client» - PullRequest
0 голосов
/ 17 июня 2020

Я пытаюсь проверить Connect2id , настроенный с помощью теста Go, и получаю следующую ошибку.

"Client authentication failed: Missing client authentication","error":"invalid_client"

Полный вывод сценария выглядит, как показано ниже.

Feature: Test Identity Provider

  Scenario:                                                             # features/idp.feature:3
    Given identity provider 'hf1-idp.json'                               # main_test.go:72 -> *Scaffold
    When I request an access token as 'cc_test'                          # main_test.go:83 -> *Scaffold
    oauth2: cannot fetch token: 401 Unauthorized
Response: {"error_description":"Client authentication failed: Missing client authentication","error":"invalid_client"}
    Then the token should have a claim 'scope'                           # main_test.go:92 -> *Scaffold
    And the token should have a claim 'sub' with value 'dips-mra'        # main_test.go:106 -> *Scaffold
    And the token should have a claim 'hso:userid' with value 'dips-mra' # main_test.go:106 -> *Scaffold

Мой hf1-idp. json файл выглядит как показано ниже.

{
  "kind": "PING",
  "issuer": "https://my.issuer.com/c2id",
  "insecure": true,
  "clients": {
    "cc_test": {
      "flow": "clientcredentials",
      "id": "clientId",
      "secret": "",
      "scopes": ["openid", "solr"],
      "values": {
          "resource": ["https://my.solrnode1.com/solr/", "https://my.solrnode2.com/solr/"]
      }
    },

Connect2id отлично работает в настроенной среде. В качестве примера я получаю ожидаемый результат, когда запускаю следующую команду Curl с правильными значениями

curl -k -s -H "Content-Type: application/json" -XPOST https://my.issuer.com/c2id/direct-authz/rest/v2 \
        -H "Authorization: Bearer ztucBearerToken" \
        -d '{
  "sub_session" : { "sub" : "alice" },
  "client_id"   : "clientId",
  "scope"       : [ "openid", "solr" ],
  "claims"      : [ "name", "email", "email_verified", "access_token:hso:subject:system", "access_token:hso:subject:id", "access_token:hso:subject:name", "access_token:hso:subject:role:system", "access_token:hso:subject:role:id", "access_token:hso:subject:role:name", "access_token:hso:subject:organization:system", "access_token:hso:subject:organization:id", "access_token:hso:subject:organization:name", "access_token:hso:subject:organization:child-organization:system", "access_token:hso:subject:organization:child-organization:id", "access_token:hso:subject:organization:child-organization:name", "access_token:hso:purpose:system", "access_token:hso:purpose:id", "access_token:hso:purpose:description", "access_token:hso:resource:system", "access_token:hso:resource:id" ]
}'

Обновлен следующими кодами

main_test. go

func (sc *Scaffold) readIdentityProvider(filename string) error {
    idp, err := idp.ReadIdentityProvider(context.Background(), "testdata/"+filename)

// More code goes here
}

provider . go

func ReadIdentityProvider(ctx context.Context, filename string) (*IdentityProvider, error) {
    config, err := readIdentityProvider(filename)
    if err != nil {
        return nil, err
    }

    return NewIdentityProvider(ctx, config)
}

func NewIdentityProvider(ctx context.Context, config *Config) (*IdentityProvider, error) {
    ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{
        Transport: &http.Transport{
            TLSClientConfig: &tls.Config{
                InsecureSkipVerify: config.Insecure,
            },
        },
    })
    provider, err := oidc.NewProvider(ctx, config.Issuer)

// More code goes here
}

oid c. go

func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
    wellKnown := strings.TrimSuffix(issuer, "/") + "/direct-authz/rest/v2"
    req, err := http.NewRequest("POST", wellKnown, nil)
    if err != nil {
        return nil, err
    }
    resp, err := doRequest(ctx, req)    // Herer I get 401 Unauthorized
    if err != nil {
        return nil, err
    }
// More code goes here
}

1 Ответ

0 голосов
/ 17 июня 2020

В запросе отсутствует токен на предъявителя. (https://connect2id.com/products/server/docs/integration/direct-authz#error -401 ) Когда вы используете curl, вы используете параметр -H для добавления токена носителя авторизации -H "Authorization: Bearer ztucBearerToken"

. То же самое необходимо сделать в вашем приложении Go.

func NewProvider(ctx context.Context, issuer string) (*Provider, error) {
    wellKnown := strings.TrimSuffix(issuer, "/") + "/direct-authz/rest/v2"
    req, err := http.NewRequest("POST", wellKnown, nil)

    bearer := "Bearer ztucBearerToken"
    req.Header.Add("Authorization", bearer)

    if err != nil {
        return nil, err
    }
    resp, err := doRequest(ctx, req)    // Herer I get 401 Unauthorized
    if err != nil {
        return nil, err
    }
// More code goes here
}

Некоторые подтверждающие факты

Аналогичное обсуждение SO идет здесь .

Чтобы получить избавиться от

400 Плохой запрос: {"error_description": "Bad request: Invalid JSON: Unnexpected token at position 0.", "error": "invalid_request"}

вам нужно передать необходимое тело запроса, как показано ниже.

req, err := http.NewRequest("POST", wellKnown, bytes.NewBuffer(bytesRepresentation))

Для получения дополнительной информации посетите Golang документацию, относящуюся к net / http

...