Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API token generation when using OIDC authentication #10597

Closed
aMozejko1 opened this issue Jan 30, 2020 · 10 comments
Closed

API token generation when using OIDC authentication #10597

aMozejko1 opened this issue Jan 30, 2020 · 10 comments
Assignees

Comments

@aMozejko1
Copy link

Hi,

I've been able to use https://github.com/goharbor/harbor/wiki/Harbor-FAQs#api to generate a Bearer token.

However when trying to authenticate using that bearer token get the error:

Failed to verify token, error: oidc: id token issued by a different provider, expected "https://OIDC-Endpoint-URL" got "https://my.harbor.url/"

If authenticating through OIDC, are users meant to generate API tokens from Harbor or from the upstream OIDC server?

This issue is a continuation of #8033 which is closed so possibly not being monitored.

@bitsf
Copy link
Contributor

bitsf commented Feb 5, 2020

@reasonerjt Do we have guide for OIDC

@Sudneo
Copy link

Sudneo commented Feb 5, 2020

Hello,

I would like to ask, how did you manage to get a proper token?

The FAQ descriptions states that in any case you need to perform an initial request with Basic Auth credentials. For a OIDC user, what credentials did you use to perform the initial request? I tried with CLI token but I am still getting 401 (except that it works from Swagger interface).

@reasonerjt
Copy link
Contributor

@Sudneo For OIDC you need to use id token to access API, basic auth is not supported.
@aMozejko1 You need to id token from the OIDC provider you configured.

@Sudneo
Copy link

Sudneo commented Mar 24, 2020

For someone who might end up on this issue, I have managed to get this working with Keycloak.

Keycloak side

Create a new user (I didn't manage to get it working with a service account), following steps similar to this.
Configure the client (that you most likely have already in place if you are using OICD for Harbor), in particular:

Authentication Flow Overrides:
          Browser Flow: browser
          Direct Grant Flow: direct grant

Onboard the user in Harbor

Go to Harbor URL and login with OICD, here use the username and password for the user you have just created.

From an admin user you might want to add this user as a Limited Guest for some of your Harbor Projects.

Retrieve a token from Keycloak and use it in Harbor.

def main():
    url = "https://[$KEYCLOAK_URL]/auth/realms/[$REALM]/protocol/openid-connect/token"
    data = {'grant_type': 'password', 'client_id': '[$HARBOR_CLIENT_NAME]', 'client_secret': '[REDACTED]',
            'scope': 'openid', 'username': '[$USER_NAME]', 'password': '[$USER_PASSWORD]'}
    response = requests.post(url, data=data)
# Get id_token from Keycloak response
    token = response.json()['id_token']
    harbor_url = "https://[$HARBOR_URL]/api/repositories/[$REPOSITORY_NAME]/tags/[$TAG]/scan"
    headers = {'authorization': f"Bearer {token}", 'Content-Type': 'application/json',
               'Accept': 'application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0'}
    harbor_response = requests.get(harbor_url, headers=headers)
#    if harbor_response.status_code == 403:
#        xsrf = __get_xsrf_token(headers['Set-Cookie'])
#        headers = {'Authorization': f"Bearer {token}", "accept": "application/json", "X-Xsrftoken": xsrf}
#        harbor_response = requests.get(harbor_url, headers=headers)
    print(harbor_response.json())

@reasonerjt
Copy link
Contributor

Thanks @Sudneo I've added a faq referencing your comment

@riteshja
Copy link

Is there an harbor api to onboard the users created in the OIDC provider or do we have to use the UI?

@christian-korneck
Copy link

does anyone know how to get the oidc token with the oidc provider Auth0 ?
I have a user account on a hosted harbor2 registry (not under my control) and would like to find out if/how I can use the API.

@gzm0
Copy link

gzm0 commented May 25, 2022

For posterity: The above example requires the Harbor client secret and user name password (I suspect it will not work with 2FA enabled). Depending on your use case, this might not be acceptable.

In this case, you can use the OAuth Implicit Grant flow:

import express from "express";
import axios from "axios";
import { Issuer, generators } from 'openid-client';

const issuer = await Issuer.discover('https://<domain>/auth/realms/<realm>');

const client = new issuer.Client({
  client_id: '<client-id>',
  response_types: ['id_token'],
});

const app = express();

app.use(express.urlencoded({ extended: true }));

const params = new Promise((resolve, rej) => {
  app.post("/", (req, res) => {
    resolve(client.callbackParams(req));
    res.send("You can close this window.");
  });
});

const listener = await new Promise((res, rej) => {
  const listener = app.listen((err) => {
    if (err) rej(err);
    else res(listener);
  });
});

const port = listener.address().port;

const redirect_uri = `http://localhost:${port}/`;

console.log(`Listening on ${port}`);

const nonce = generators.nonce();

const url = client.authorizationUrl({
  scope: 'openid email profile',
  response_mode: 'form_post',
  redirect_uri,
  nonce,
});

// Open this in a browser, log in.
console.log(url);

const { id_token } = await client.callback(redirect_uri, await params, { nonce });

const log = await axios({
  url: 'https://<harbor-host>/api/v2.0/audit-logs?page=1&page_size=10',
  headers: {
    accept: "application/json",
    authorization: `Bearer ${id_token}`,
  },
});

console.log(log);

@maheshsmartcow
Copy link

Is there an harbor api to onboard the users created in the OIDC provider or do we have to use the UI?

Is there any solution for this now ? I create a user in keycloak and I need to upload my own secret for a specific user. But until I login manually into Harbor UI through OIDC, the account is not created in harbor. So I am looking for an API solution to achieve the flow through automation

@rgarcia89
Copy link
Contributor

rgarcia89 commented Feb 12, 2024

I am very happy to see that the bearer token functionality has been implemented in Harbor. However, I would prefer if Harbor could generate a token that I could use for authentication via the CLI. The OIDC bearer token method only works when providing a client_id and client_secret, and I am usually hesitant to share the latter. Harbor however is already aware of all these information.

I am doing a similar thing for hashicorp vault already. There you can trigger a login using the vault binary with the following command vault login -method=oidc role=oidc and obtain by that a token which you use to authenticate. https://registry.terraform.io/providers/hashicorp/vault/latest/docs#provider-arguments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants