<@U04UQ68083H> how to add oauth webhook for a spec...
# ory-copilot
b
@chilly-king-10285 how to add oauth webhook for a specific client instead of all oauth clients
c
A message from kapa.ai
To add a webhook for a specific OAuth client, you can use the Ory CLI to register your webhook endpoint in your OAuth2 configuration. Here are the steps: 1. Use the Ory CLI to register your webhook endpoint. You can choose to add authentication in the header, in the cookie, or have no authentication. Here are the commands for each: - With authentication in header:
Copy code
bash      ory patch oauth2-config $project_id \          --add '/oauth2/token_hook/url="<https://my-example.app/token-hook>"' \          --add '/oauth2/token_hook/auth/type="api_key"' \          --add '/oauth2/token_hook/auth/config/in="header"' \          --add '/oauth2/token_hook/auth/config/name="X-API-Key"' \          --add '/oauth2/token_hook/auth/config/value="MY API KEY"' \          --format yaml
- With authentication in cookie:
Copy code
bash      ory patch oauth2-config $project_id \          --add '/oauth2/token_hook/url="<https://my-example.app/token-hook>"' \          --add '/oauth2/token_hook/auth/type="api_key"' \          --add '/oauth2/token_hook/auth/config/in="cookie"' \          --add '/oauth2/token_hook/auth/config/name="X-Cookie-Name"' \          --add '/oauth2/token_hook/auth/config/value="MY SECRET COOKIE"' \          --format yaml
- No authentication:
Copy code
bash      ory patch oauth2-config $project_id \          --add '/oauth2/token_hook="<https://my-example.app/token-hook>"' \          --format yaml
2. Update the OAuth2 client configuration to use the webhook. You can do this using the Ory Console, Ory CLI, Ory SDK, or REST API. Here's an example using the Ory SDK:
Copy code
javascript    import { Configuration, OAuth2Api, OAuth2Client } from "@ory/client"         const ory = new OAuth2Api(        new Configuration({          basePath: `https://${process.env.ORY_PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,          accessToken: process.env.ORY_API_KEY,        }),      )         export async function updateOAuth2Client(        id: string,        update: Partial<OAuth2Client>,      ) {        // setOAuth2Client replaces all values (empty ones too),        // which is why we include the original client.        const { data: original } = await ory.getOAuth2Client({ id })        await ory.setOAuth2Client({          id,          oAuth2Client: {            ...original,            ...update,          },        })      }
Please replace
$project_id
and
id
with your actual project ID and client ID respectively. Also, replace the URLs and keys with your actual values. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/hydra/guides/claims-at-refresh#configuration) and [Ory API documentation](https://www.ory.sh/docs/reference/api#tag/oAuth2/operation/setOAuth2Client).
b
@chilly-king-10285 can you show how to update the client using the API or CLI?
c
A message from kapa.ai
Sure, you can update an OAuth 2.0 client using either the Ory CLI or the REST API. Using the Ory CLI: Here's an example of how to update a client using the Ory CLI:
Copy code
bash hydra update client <client-id-here> -c <http://localhost/cb> -g authorization_code -r code -a core,foobar
In this command, replace
<client-id-here>
with the ID of the client you want to update. The
-c
flag sets the callback URL,
-g
sets the grant type,
-r
sets the response type, and
-a
sets the allowed scopes. To encrypt an auto-generated OAuth2 Client Secret, use flags
--pgp-key
,
--pgp-key-url
or
--keybase
flag, for example:
Copy code
bash hydra update client e6e96aa5-9cd2-4a70-bf56-ad6434c8aaa2 -n "my app" -g client_credentials -r token -a core,foobar --keybase keybase_username
You can find more details in the [Ory CLI documentation](https://www.ory.sh/docs/hydra/cli/hydra-update-client#hydra-update-client). Using the REST API: Here's an example of how to update a client using the REST API with the Ory SDK:
Copy code
javascript import { Configuration, OAuth2Api, OAuth2Client } from "@ory/client"  const ory = new OAuth2Api(   new Configuration({     basePath: `https://${process.env.ORY_PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,     accessToken: process.env.ORY_API_KEY,   }), )  export async function updateOAuth2Client(   id: string,   update: Partial<OAuth2Client>, ) {   // setOAuth2Client replaces all values (empty ones too),   // which is why we include the original client.   const { data: original } = await ory.getOAuth2Client({ id })   await ory.setOAuth2Client({     id,     oAuth2Client: {       ...original,       ...update,     },   }) }
In this code, replace
id
with the ID of the client you want to update, and
update
with the new configuration for the client. You can find more details in the [Ory API documentation](https://www.ory.sh/docs/reference/api#tag/oAuth2/operation/setOAuth2Client).
b
@chilly-king-10285 update a single oauth client to use a webhook using the CLI or API
c
A message from kapa.ai
I'm sorry, but the provided knowledge sources do not contain information on how to update a single OAuth client to use a webhook using the CLI or API. The sources discuss how to update an OAuth client, but they do not specify how to add a webhook to a client. For accurate information, I recommend checking the official Ory documentation or the API reference for the specific method to add a webhook to an OAuth client.
b
@chilly-king-10285 how would I add custom info to user sessions? For example the user's permissions
c
A message from kapa.ai
You can add custom information to user sessions during the consent acceptance process. This can be done by including any information in the
session
object when accepting the consent request. This information will then be included in the response. Here is an example of how to do this using the Ory SDK:
Copy code
javascript import { Configuration, OAuth2Api } from "@ory/client"  const ory = new OAuth2Api(   new Configuration({     basePath: `https://${process.env.ORY_PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,     accessToken: process.env.ORY_API_KEY,   }), )  export async function acceptConsent(consentChallenge: string) {   const { data } = await ory.getOAuth2ConsentRequest({ consentChallenge })    return await ory     .acceptOAuth2ConsentRequest({       consentChallenge: consentChallenge,       acceptOAuth2ConsentRequest: {         session: {           access_token: {             some_custom_claim: "some_custom_value",           },           id_token: {             id_custom_claim: "some_value",           },         },       },     })     .then(({ data }) => data) }
In this example,
some_custom_claim
and
id_custom_claim
are custom claims added to the
access_token
and
id_token
respectively. You can replace these with the user's permissions or any other custom information you want to include in the user session. Please note that the
/userinfo
endpoint is publicly available, so its contents are as visible as those of ID Tokens. Therefore, it's important not to expose sensitive information without user consent. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/userinfo-oidc#adding-custom-claims-to-the-userinfo-response).
b
@chilly-king-10285 how to use oauth to login human users
c
A message from kapa.ai
To use OAuth to log in human users, you can follow these steps: 1. Initiate the OAuth2 2.0 / OpenID Connect Flow by pointing the end user's browser to the
/oauth2/auth
endpoint. Depending on the OAuth2 flow you want to use, some of the query parameters can change. For example,
/oauth2/auth?response_type=code
or
/oauth2/auth?response_type=token
. 2. Ory OAuth2 and OpenID Connect will check if a session cookie is set containing information about a previously successful login. Additionally, OpenID Connect parameters
id_token_hint
,
prompt
, and
max_age
are evaluated and processed. Depending on their values and the login state, the user might need to re-authenticate or the flow will fail. 3. To authenticate the user, Ory OAuth2 and OpenID Connect redirects the browser to the "login endpoint" established in your config. For example:
Copy code
bash    ory patch oauth2-config        --replace "/urls/login=\"<https://login.example.org/oauth2-login\>""
4. Ory OAuth2 and OpenID Connect appends a
login_challenge
query parameter to the URL. The value is an ID which should later be used by the login endpoint to fetch important information about the request. 5. The way you authenticate the end user is up to you. In most cases, you will show an HTML form similar to:
Copy code
html    <form action="/login" method="post">        <input type="hidden" name="csrf_token" value="...." />        <!-- Use CSRF tokens in your HTML forms! -->        <input type="email" name="login_email" placeholder="Please enter your email address to log in" />        <input type="password" name="login_password" />        <input type="checkbox" name="remember" value="Remember me on this device" />        <input type="submit" value="Log in" />      </form>
For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/custom-login-consent/flow#login).
b
@chilly-king-10285 if I have a JWT created from toSession method, how would I check that JWT's validity?
c
A message from kapa.ai
To verify the validity of a JSON Web Token (JWT) obtained from the
toSession
method, you can use the public key from the JSON Web Key Set (JWKS). Here's how you can do it: 1. Export the public key from the JWKS:
Copy code
bash ory get jwk some-example-set \    --public \    --project {project.id} --format json-pretty \    > es256-public.jwks.json
2. Use the exported public key to verify the JWT. The specific method to do this will depend on the programming language and JWT library you are using. Most JWT libraries provide a method to validate a token using a public key. Please replace
some-example-set
and
{project.id}
with your actual JWKS set and project ID respectively. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/identities/session-to-jwt-cors#end-to-end-example).
b
@chilly-king-10285 if we have an oauth client configured to return jwt's, what jwk is used? How can we verify the signature?
c
A message from kapa.ai
In Ory, the JSON Web Key (JWK) used to sign the JWTs is determined by the cryptographic keys configured for the OAuth2 client. The two most commonly used cryptographic keys in Ory are RS256 and ES256. RS256 is an asymmetric cryptographic algorithm that generates a public key and a private key. The private key is used to sign the token, while the public key is used to verify its signature. ES256, on the other hand, is a variant of the elliptic curve algorithm, which is more efficient than RSA ([source](https://www.ory.sh/docs/hydra/jwks)). To verify the signature of a JWT, you can use the public key from the JSON Web Key Set (JWKS). Ory exposes a standard endpoint that contains the public keys for verifying ID tokens and JWT access tokens. This endpoint is
/.well-known/jwks.json
and is available for each Ory Network project at
https://{project.slug}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>
([source](https://www.ory.sh/docs/hydra/jwks#the-role-of-well-knownjwksjson)). You can also use the
jwt
authenticator in Ory Oathkeeper to handle requests that have a Bearer Token in the Authorization Header. It assumes that the token is a JSON Web Token and tries to verify the signature of it ([source](https://www.ory.sh/docs/oathkeeper/pipeline/authn#jwt)). Please replace
{project.slug}
with your actual project slug.
b
@chilly-king-10285 JWKS_B64_ENCODED=$(cat rs256.jwks.json | base64 | tr -d '\n') JSONNET_B64_ENCODED=$(cat claims.jsonnet | base64 | tr -d '\n') PATCH_ARG='/session/whoami/tokenizer/templates/jwt_maverick_template={"jwks_url":"base64://'$JWKS_B64_ENCODED'","claims_mapper_url":"base64://'$JSONNET_B64_ENCODED'","ttl":"10m"}' ory patch identity-config ecaaa3cb-0730-4ee8-a6df-9553cdfeef89 --add "$PATCH_ARG" --format yaml The requested action was forbidden
c
A message from kapa.ai
The error message "The requested action was forbidden" typically indicates that the operation you're trying to perform is not allowed. This could be due to a variety of reasons such as insufficient permissions, incorrect project ID, or an invalid API key. Here are a few things you can check: 1. API Key: Ensure that the API key you're using has the necessary permissions to perform the operation. If you're not sure, you can create a new API key with the appropriate permissions. 2. Project ID: Make sure that the project ID
ecaaa3cb-0730-4ee8-a6df-9553cdfeef89
is correct and that it belongs to the account associated with the API key. 3. Identity Configuration: Verify that the identity configuration you're trying to patch exists and that you have the necessary permissions to modify it. If you're still encountering issues, I recommend referring to the [Ory documentation](https://www.ory.sh/docs/) or reaching out to the Ory community for further assistance.
b
@chilly-king-10285 how to get current identity config
c
A message from kapa.ai
You can get the current identity configuration for a specific Ory Network project using the Ory CLI. Here's how you can do it:
Copy code
bash ory get identity-config [project-id] [flags]
Replace
[project-id]
with the ID of your project. You can find the
project_id
in the Ory Network dashboard or by using
ory list projects
. Here are some examples:
Copy code
bash $ ory get identity-config ecaaa3cb-0730-4ee8-a6df-9553cdfeef89 --format yaml > identity-config.yaml      $ ory get identity-config ecaaa3cb-0730-4ee8-a6df-9553cdfeef89 --format json
These commands will get the identity configuration for the project with ID
ecaaa3cb-0730-4ee8-a6df-9553cdfeef89
and output it in YAML or JSON format. For more details, you can refer to the [Ory CLI documentation](https://www.ory.sh/docs/cli/ory-get-identity-config#ory-get-identity-config).
b
@chilly-king-10285 if I'm getting a jwt from toSession in the front-end, how do I make sure we get a new jwt before the current one expires?
c
A message from kapa.ai
To ensure that you get a new JWT before the current one expires, you can implement a mechanism in your front-end application to refresh the JWT at a certain interval. This interval should be less than the JWT's expiry time. Here's a basic example of how you can do this using JavaScript's
setInterval
function:
Copy code
javascript import { Configuration, FrontendApi, Session } from "@ory/client"    const frontend = new FrontendApi(     new Configuration({       basePath: "<http://localhost:4000>", // Use your local Ory Tunnel URL       baseOptions: {         withCredentials: true,       },     }),   )    export function checkSession() {     const [session, setSession] = useState<Session>(undefined)      useEffect(() => {       const interval = setInterval(() => {       frontend           .toSession()           .then(({ data: session }) => {             setSession(session)           })           .catch((error) => {             // Handle error           })       }, 1000 * 60 * 5); // Refresh every 5 minutes      return () => clearInterval(interval); // Clear interval on component unmount   }, [])      return session;   }
In this example, the
checkSession
function will refresh the session every 5 minutes. You should adjust this interval based on your JWT's expiry time. Please note that this is a simplified example and may not cover all edge cases. For instance, if the user's session is invalidated on the server-side (e.g., the user logs out), the client-side session will still be considered valid until the next refresh. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks).
b
@chilly-king-10285 how to update an existing tokenizer template in identity config
c
A message from kapa.ai
To update an existing tokenizer template in the identity configuration, you can use the
ory patch identity-config
command with the
--replace
flag. Here's an example:
Copy code
bash ory patch identity-config [project-id] --replace "/session/whoami/tokenizer/templates/[template-name]={new-template}" --format yaml
Replace
[project-id]
with the ID of your project,
[template-name]
with the name of the template you want to update, and
{new-template}
with the new template configuration. Here's a more concrete example:
Copy code
bash ory patch identity-config ecaaa3cb-0730-4ee8-a6df-9553cdfeef89 --replace "/session/whoami/tokenizer/templates/jwt_template_1={jwks_url: base64://..., claims_mapper_url: base64://..., ttl: 1m}" --format yaml
In this example,
jwt_template_1
is the name of the template being updated, and
jwks_url
,
claims_mapper_url
, and
ttl
are the new template configuration. Please note that you need to replace
ecaaa3cb-0730-4ee8-a6df-9553cdfeef89
and
base64://...
with your actual project ID and base64-encoded JWKS and Jsonnet template respectively. For more details, you can refer to the [Ory CLI documentation](https://www.ory.sh/docs/cli/ory-patch-identity-config#ory-patch-identity-config).
b
@chilly-king-10285 is there a way to use the pregenerated jwks at /.well-known/jwks.json for a tokenizer template?
c
A message from kapa.ai
Yes, you can use the pre-generated JWKS for a tokenizer template. The JWKS endpoint is exposed by default for each Ory Network project at
https://{{project.slug}}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>
. When you're setting up your tokenizer template, you can specify the
jwks_url
to point to this endpoint. Here's an example:
Copy code
bash ory patch identity-config [project-id] --replace "/session/whoami/tokenizer/templates/[template-name]={{jwks_url: 'https://{{project.slug}}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>', claims_mapper_url: base64://..., ttl: 1m}}" --format yaml
Replace
[project-id]
with the ID of your project,
[template-name]
with the name of the template you want to update, and
{{project.slug}}
with your actual project slug. The
claims_mapper_url
and
ttl
should be replaced with your actual Jsonnet template and desired time-to-live respectively. Please note that the JWKS endpoint contains the public keys for verifying ID tokens and JWT access tokens. The actual keys used for signing the tokens are determined by the cryptographic key management and JSON Web Key Sets (JWKS) configuration of your Ory setup. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/hydra/jwks#the-role-of-well-knownjwksjson).
b
@chilly-king-10285 does jwks_url have to be base64 encoded?
c
A message from kapa.ai
No, the
jwks_url
does not have to be base64 encoded. It should be a string containing the URL of the JSON Web Key Set (JWKS). For example:
Copy code
bash jwks_url: 'https://{{project.slug}}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>'
In this case,
{{project.slug}}
should be replaced with your actual project slug. However, please note that if you're providing a Jsonnet template or a JWKS as a string directly in the configuration (instead of via a URL), then those should be base64-encoded. This is because these could potentially be multi-line strings, and base64 encoding ensures they can be safely included in the configuration. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/hydra/jwks#the-role-of-well-knownjwksjson).
b
Copy code
jwks_url: 'https://{{project.slug}}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>'
This results in this error JWKS URL must be a base64 literal (base64://)
@chilly-king-10285
Copy code
jwks_url: 'https://{{project.slug}}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>'
This results in this error JWKS URL must be a base64 literal (base64://)
c
A message from kapa.ai
I apologize for the confusion. It appears that in the context of Ory Network's tokenizer templates, the
jwks_url
does indeed need to be base64-encoded. This is likely because the configuration expects a base64-encoded string that it can decode into the actual JWKS or Jsonnet template. Here's how you can base64-encode the JWKS URL:
Copy code
bash JWKS_URL_B64_ENCODED=$(echo -n 'https://{{project.slug}}.<http://projects.oryapis.com/.well-known/jwks.json|projects.oryapis.com/.well-known/jwks.json>' | base64 | tr -d '\n')
Then, you can use this base64-encoded JWKS URL in your tokenizer template:
Copy code
bash ory patch identity-config [project-id] --replace "/session/whoami/tokenizer/templates/[template-name]={{jwks_url: 'base64://'$JWKS_URL_B64_ENCODED, claims_mapper_url: base64://..., ttl: 1m}}" --format yaml
Please replace
{{project.slug}}
,
[project-id]
,
[template-name]
, and
base64://...
with your actual project slug, project ID, template name, and base64-encoded Jsonnet template respectively. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/identities/session-to-jwt-cors#end-to-end-example).
b
@chilly-king-10285 how to change the jwk an oauth client is using for the signature
c
A message from kapa.ai
To change the JSON Web Key (JWK) that an OAuth2 client is using for the signature, you can use the
PUT /admin/keys/{set}/{kid}
endpoint of the Ory Hydra API. This endpoint allows you to set a new JWK for a given key set and key id. Here's an example of how you can do this:
Copy code
bash curl -X PUT "<https://your-hydra-instance.com/admin/keys/{set}/{kid}>" \      -H "Content-Type: application/json" \      -d '{            "keys": [              {                "kty": "RSA",                "e": "AQAB",                "n": "your-new-public-key",                "alg": "RS256",                "kid": "your-key-id",                "use": "sig"              }            ]          }'
Replace
{set}
with the key set id,
{kid}
with the key id, and
"n": "your-new-public-key"
with your new public key. Please note that you need to have the necessary permissions to perform this operation. Also, the new key should be compatible with the algorithm (
alg
) specified in the request. For more details, you can refer to the [Ory Hydra API documentation](https://www.ory.sh/docs/hydra/reference/api#set-json-web-key).
b
@chilly-king-10285 how to change the jwk an oauth client is using for the signature in ory network
c
A message from kapa.ai
To change the JSON Web Key (JWK) that an OAuth2 client is using for the signature in Ory Network, you need to register the new public key with the OAuth2 client. This can be done using the
jwks_uri
or
jwks
fields of the client. The
jwks_uri
is a URL that points to a JSON Web Key Set (JWKS) that contains the public key. The
jwks
field is a direct JSON object representation of the JWKS. Here is an example of how to register a new RSA public key for an OAuth2 client:
Copy code
javascript import { Configuration, OAuth2Api } from "@ory/client"      const ory = new OAuth2Api(     new Configuration({       basePath: `https://${process.env.ORY_PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,       accessToken: process.env.ORY_API_KEY,     }),   )      export async function createOAuth2Client() {     await ory.createOAuth2Client({       oAuth2Client: {         token_endpoint_auth_method: "private_key_jwt",         token_endpoint_auth_signing_alg: "RS256", // or ES256, EdDSA; ...         // ...            // define the new public key directly:         jwks: {           keys: [             {               kty: "RSA",               n: "your-new-public-key",               e: "AQAB",               use: "sig",               kid: "some-key-id",             },           ],         },            // or alternatively tell Ory to fetch it from an URL:         jwks_uri: "<https://path-to-my-public/keys.json>",       },     })   }
Replace
"n": "your-new-public-key"
with your new public key. Please note that you need to have the necessary permissions to perform this operation. Also, the new key should be compatible with the algorithm (
token_endpoint_auth_signing_alg
) specified in the request. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/hydra/guides/jwt#registering-the-clients-public-key).