<@U04UQ68083H> How to use biometrics with Ory. Can...
# ory-copilot
b
@chilly-king-10285 How to use biometrics with Ory. Can you use biometrics with the default Account Experience?
c
A message from kapa.ai
New message text here
b
@chilly-king-10285 how to do role inheritance with OPL
c
A message from kapa.ai
Role inheritance can be implemented in Ory using Hierarchical Role Based Access Control (HRBAC). In HRBAC, roles can inherit permissions from other roles. For example, an "administrator" role could inherit all permissions from the "moderator" role. This reduces duplication and management complexity around defining privileges. However, the Ory Permission Language (OPL) examples provided in the knowledge sources do not directly show how to implement role inheritance. The OPL is used to define permissions and relationships in a more granular way, such as defining that a user can view or edit a document. To implement role inheritance, you would typically define roles as groups of permissions, and then specify that one role inherits the permissions of another role. This could potentially be done in OPL by defining a role as a class with a set of permissions, and then creating another class that extends the first class to inherit its permissions. For more detailed guidance on how to implement role inheritance in Ory, you may want to refer to the Ory documentation or seek advice from the Ory community. Here are the relevant knowledge sources: - [Ory Permission Language](https://www.ory.sh/docs/keto#ory-permission-language) - [Role Based Access Control (RBAC)](https://www.ory.sh/docs/keto/guides/rbac)
b
@chilly-king-10285 if users can create custom roles, then how do we prevent race conditions when writing the permission role
c
A message from kapa.ai
Ory Keto, the underlying permission server for Ory Permissions, is designed to handle a large number of concurrent requests without sacrificing performance or reliability. This includes handling potential race conditions when multiple users are trying to create or modify roles at the same time. However, the knowledge sources provided do not specifically address how to prevent race conditions when writing custom roles. In general, race conditions can be prevented by using locks or other synchronization mechanisms to ensure that only one user can modify a role at a time. For more detailed guidance on how to prevent race conditions when writing custom roles in Ory, you may want to refer to the Ory documentation or seek advice from the Ory community. Here are the relevant knowledge sources: - [Ory Keto Overview](https://www.ory.sh/docs/keto) - [Create a permission model](https://www.ory.sh/docs/keto/modeling/create-permission-model) - [Ory Permission Language](https://www.ory.sh/docs/keto#ory-permission-language)
b
@chilly-king-10285 if you create a custom UI, can you replace a single flow or do you have to replace the entire Account Experience?
c
A message from kapa.ai
Yes, you can replace a single flow with a custom UI while using Ory. You don't have to replace the entire Account Experience. To define the paths where Ory calls your custom UI, you can go to the Ory Console → User Interface. This view allows you to define the URLs of UI views for every self-service flow. You can use relative or absolute paths to point to the desired UI. By default, self-service flows use Ory Account Experience, which is a part of every Ory Network project. In the default setup, the system uses relative paths to point to the appropriate UI for every screen. The relative links that point to the Ory Account Experience follow the
/ui/{flow_name}
format. If you want to replace a single flow, you can set a custom UI base URL for that specific flow. When you define a custom UI base URL, you lose access to the Ory Account Experience for that specific flow. The custom UI base URL takes precedence over the SDK Configuration URL. For more details, you can refer to the [Ory documentation](https://www.ory.sh/docs/kratos/bring-your-own-ui/configure-ory-to-use-your-ui).
b
@chilly-king-10285 how would an end user create a custom role in Ory if using HRBAC
c
A message from kapa.ai
In Ory's Hierarchical Role Based Access Control (HRBAC) system, roles and permissions are typically managed by administrators or through automated processes, not directly by end users. The HRBAC system maps subjects (users) to roles and roles to permissions, making permission management more convenient by grouping subjects in roles and assigning permissions to roles. While the provided knowledge sources do not specifically detail how an end user would create a custom role, it's important to note that allowing end users to create custom roles could potentially lead to security risks, as users could grant themselves elevated permissions. If you still want to allow end users to create custom roles, you would need to build a custom interface or API that interacts with Ory's APIs to create and manage roles. This would involve writing custom code and would need to be done carefully to ensure security and proper access control. For more information on how to implement HRBAC with Ory, you can refer to the [Ory documentation](https://www.ory.sh/docs/keto/guides/rbac).
b
@chilly-king-10285 what is a typically pattern for ory environments. How should ory environments map to application environments?
c
A message from kapa.ai
Ory Network offers different environments for production, staging, and development. These are called Ory Network projects. - Development projects provide a free test environment for your projects, with limited rate limits and no custom domain. They are ideal for early-stage development and testing. - Staging projects offer all features of a production environment including a custom domain. Staging projects have lower rate limits than production projects. They are suitable for testing your application and its integrations with Ory Network before deploying to production. These environments should map to your application environments in a similar way. For example, when you are developing your application, you should use the Ory development environment. When you are ready to test your application, you should use the Ory staging environment. And when you are ready to deploy your application, you should use the Ory production environment. This approach allows you to test and validate your application's integration with Ory at each stage of the development process, without affecting your production data or users. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/getting-started/local-development#environments).
b
@chilly-king-10285 Give example of querying permissions with Ory JS SDK
c
A message from kapa.ai
Sure, here's an example of how to check permissions using the Ory JavaScript SDK. This example is based on the upgrade guide for the SDK V1:
Copy code
javascript // Check a permission   const isAllowed = await ory   .permission   .checkPermission({namespace: "n", /* ... */})   .then(({data}) => data.allowed)
In this example,
ory
is an instance of the Ory client,
permission
is the permissions module, and
checkPermission
is the method to check a permission. The method takes an object with the details of the permission to check, and returns a promise that resolves to an object with a
data
property. The
data
property is an object with an
allowed
property, which is
true
if the permission is granted and
false
otherwise. Please note that you need to replace
"n"
and
/* ... */
with the actual values for your use case. For more information, you can refer to the [Ory SDK V1 upgrade guide](https://www.ory.sh/docs/guides/upgrade/sdk-v1#permissions--access-control).
b
@chilly-king-10285 what the import statement for that? And is there more detailed SDK documentation somewhere?
c
A message from kapa.ai
To use the Ory JavaScript SDK, you would typically import it into your project like this:
Copy code
javascript import { Configuration, PublicApi, AdminApi } from "@ory/client"
In this example,
Configuration
,
PublicApi
, and
AdminApi
are being imported from the
@ory/client
package. For more detailed SDK documentation, you can refer to the autogenerated documentation available on GitHub. Here are some examples: - [OAuth2Api API](https://github.com/ory/hydra-client-go/blob/master/docs/OAuth2Api.md) - [OidcApi API](https://github.com/ory/hydra-client-go/blob/master/docs/OidcApi.md) Please note that these links point to the Go SDK documentation, but they can give you an idea of what methods are available. The JavaScript SDK should have similar methods. For more specific information about the JavaScript SDK, you may want to refer to the [Ory JavaScript SDK documentation](https://www.ory.sh/docs/hydra/sdk/js).
b
@chilly-king-10285 how to view openapi spec of JS SDK
c
A message from kapa.ai
The OpenAPI specification for the Ory JavaScript SDK is not directly provided in the knowledge sources. However, Ory uses the
openapi-generator
to generate its SDKs, which means the SDKs are based on an OpenAPI specification. You can view the source code for the generated Ory SDKs on the [Ory SDK GitHub repository](https://github.com/ory/sdk). The OpenAPI specification used to generate the SDKs might be included in the repository, or you might be able to generate it using the
openapi-generator
. For more detailed information, you may want to refer to the [Ory SDK documentation](https://www.ory.sh/docs/sdk) or the [
openapi-generator
GitHub repository](https://github.com/OpenAPITools/openapi-generator).
b
@chilly-king-10285 if you need an API key to call the check permission API, then aren't you effectively giving that service carte blanche access to the API?
c
A message from kapa.ai
Yes, an API key is typically used to authorize privileged operations, such as calling the Admin API. However, the level of access that an API key provides can be controlled and limited based on your needs. In Ory, API keys are bound to a specific project and work only in the context of that project. This means that any user or service with access to the API key can perform the operations that the API key allows within that project. Therefore, it's crucial to keep your API keys secure and rotate them if necessary. While the API key does provide access to the API, it doesn't necessarily mean that the service has carte blanche access to all operations. The actual permissions granted to an API key can be controlled and limited based on your needs. For example, you could create an API key that only has permission to call the
check_permission
API and not any other APIs. This would allow a service to check permissions without being able to modify permissions or perform other potentially harmful operations. For more information on how to manage API keys in Ory, you can refer to the [Ory documentation](https://www.ory.sh/docs/concepts/personal-access-token#authorizing-ory-network-project-admin-apis).
b
@chilly-king-10285 how to restrict an api key to only be able to do specific operations?
c
A message from kapa.ai
The provided knowledge sources do not contain specific information on how to restrict an API key to only be able to do specific operations in Ory. However, in general, the scope of an API key's access can be controlled at the time of its creation. This is typically done by assigning specific roles or permissions to the API key. For more detailed guidance on how to restrict an API key's access in Ory, you may want to refer to the [Ory documentation](https://www.ory.sh/docs/concepts/personal-access-token#authorizing-ory-network-project-admin-apis) or seek advice from the Ory community.
b
@chilly-king-10285 ory makes the distinction between admin and frontend apis. How do I know whether an endpoint is admin or frontend?
c
A message from kapa.ai
Ory distinguishes between Admin APIs and Frontend (or Public) APIs. Admin APIs are used for privileged operations such as deleting users or creating permissions. They require an Ory Network API Key for authorization. Frontend APIs (also referred to as Public APIs) are used to interact with Ory Network projects from your frontend application and do not require any special authorization. They are typically used for operations like registering users or checking login state. To determine whether an endpoint is an Admin or Frontend API, you can refer to the Ory API documentation. The documentation will specify whether an endpoint is part of the Admin or Frontend APIs. For example, in the [Ory API Reference](https://www.ory.sh/docs/reference/api), endpoints used by frontend applications to manage a user's own profile are listed under "Ory APIs - frontend". Similarly, in the [Ory Network API Authorization](https://www.ory.sh/docs/concepts/personal-access-token) documentation, it's mentioned that Ory Network Frontend APIs are used to interact with Ory Network projects, such as registering users or checking login state, while Ory Network Admin APIs are used to perform privileged operations. In general, if an endpoint requires an API key for authorization, it's likely an Admin API. If it doesn't require an API key, it's likely a Frontend API.
b
@chilly-king-10285 describe collaborator roles in ory project
c
A message from kapa.ai
The provided knowledge sources do not contain specific information on collaborator roles in an Ory project. However, in general, collaborator roles in a project are used to control access to the project and its resources. Different roles might have different permissions, such as read, write, or admin access. For more detailed information on collaborator roles in Ory, you may want to refer to the [Ory documentation](https://www.ory.sh/docs) or seek advice from the Ory community.
b
@chilly-king-10285 example of using permissionapi with TS SDK
c
A message from kapa.ai
The provided knowledge sources do not contain a specific example of using the
PermissionApi
with the TypeScript SDK in Ory. However, you can refer to the [Ory SDK documentation](https://www.ory.sh/docs/sdk) for general information on how to use the SDKs. For more specific examples and guidance, you may want to check the [Ory GitHub repositories](https://github.com/ory/sdk) or seek advice from the Ory community.
b
@chilly-king-10285 send ory session cookie to backend and get user id from it
c
A message from kapa.ai
To send the Ory session cookie to the backend and get the user ID from it, you can use the
/sessions/whoami
endpoint. This endpoint uses the HTTP headers in the GET request to determine who is authenticated. When the request is successful, it adds the user ID to the 'X-Kratos-Authenticated-Identity-Id' header in the response. Here's an example of how to call this endpoint from a server-side application:
Copy code
javascript // pseudo-code example router.get('/protected-endpoint', async function (req, res) {   const session = await client.toSession(undefined, req.header('cookie'))   console.log(session) })
In this example,
client.toSession
is called with the
cookie
header from the request. The function returns a session object, which includes the user ID. If you're calling this endpoint from a non-browser application (e.g. a mobile app), you must include the session token:
Copy code
javascript // pseudo-code example ... const session = await client.toSession("the-session-token") console.log(session)
In this case,
client.toSession
is called with the session token. Again, the function returns a session object, which includes the user ID. For more information, you can refer to the [Ory API Reference](https://www.ory.sh/docs/reference/api).
b
@chilly-king-10285 how to call tosession with a cookie using JS SDK
c
A message from kapa.ai
To call the
toSession
method with a cookie using the Ory JavaScript SDK, you can use the
FrontendApi
class. Here's an example:
Copy code
javascript import { Configuration, FrontendApi } from "@ory/client"  const frontend = new FrontendApi(  new Configuration({    basePath: "<http://localhost:4000>", // Use your local Ory Tunnel URL    baseOptions: {      withCredentials: true,    },  }), )  const session = await frontend  .toSession({ cookie: "ory_session_...=..." })  .catch((err) => {    // Check the error to see if it's a 401 / 403 -> not logged in  })
In this example,
frontend
is an instance of the
FrontendApi
class. The
toSession
method is called with an object that includes the
cookie
property. The method returns a promise that resolves to a session object if the user is logged in, or rejects with an error if the user is not logged in. Please replace
"ory_session_...=..."
with the actual session cookie. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/identities/sign-in/check-session-token-cookie-api).
b
@chilly-king-10285 is there a way to run ory tunnel in detatched mode? i.e. it just starts the tunnel and then continues
c
A message from kapa.ai
Yes, you can run the Ory tunnel in detached mode by appending an ampersand (
&
) at the end of the command. This will run the process in the background. Here's an example:
Copy code
bash $ ory tunnel --project <your-project-slug> <https://www.example.org> &
In this example, replace
<your-project-slug>
with the slug of your project. The
&
at the end of the command runs the process in the background. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/cli/ory-tunnel#ory-tunnel).
b
@chilly-king-10285 What is the recommended way to do machine to machine authorization? If it is with OAuth, then is it recommended that backend services will need to handle both cookies and tokens?
c
A message from kapa.ai
The recommended way to do machine-to-machine authorization in Ory is with OAuth2 and OpenID Connect. OAuth2 provides a secure and scalable way to authenticate machine-to-machine requests. However, it's important to note that OAuth2 is an authorization protocol that allows users to grant consent to third-party applications to access their data. It's often misunderstood as a Login solution when, in fact, it's an authorization protocol. As for handling both cookies and tokens, Ory does check for both the cookie and the token, which means that your API must handle both Ory Session Cookies and Ory Session Tokens. Here's an example of how to do this in a Node.js Express application:
Copy code
javascript const express = require("express")   const app = express()   const { FrontendApi, Configuration } = require("@ory/client")      const ory = new FrontendApi(    new Configuration({    basePath: `https://${process.env.PROJECT_SLUG}.<http://projects.oryapis.com|projects.oryapis.com>`,    }),   )      app.get("/blog/posts", async function (req, res) {    const authHeader = req.headers.authorization    const hasAuthHeader = authHeader.startsWith("Bearer ")    const sessionToken = hasAuthHeader    ? authHeader.slice(7, authHeader.length)    : null       const session = await ory    .toSession({    cookie: req.cookies.join("; "),    xSessionToken: sessionToken,    })    .catch((err) => {    // Check the error to see if it's a 401 / 403 -> not logged in    })   })      app.listen(3000, function () {    console.log("Listening on <http://localhost:3000%22|http://localhost:3000">)   })
For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/hydra/concepts/before-oauth2) and [Ory API Reference](https://www.ory.sh/docs/identities/sign-in/check-session-token-cookie-api).
b
@chilly-king-10285 how to verify a jwt converted from an ory session?
c
A message from kapa.ai
To verify a JWT (JSON Web Token) converted from an Ory session, you can use the public key from the JSON Web Key Set (JWKS). Here's an example of how to do this: First, you need to export the public key:
Copy code
bash ory get jwk some-example-set \    --public \    --project {project.id} --format json-pretty \    > es256-public.jwks.json
In this example, replace
some-example-set
with the name of your key set and
{project.id}
with the ID of your project. The command exports the public key to a file named
es256-public.jwks.json
. Next, you can use the public key to verify the JWT. The exact method to do this depends on the library you're using. For example, if you're using the
jsonwebtoken
library in Node.js, you can do something like this:
Copy code
javascript const jwt = require('jsonwebtoken'); const fs = require('fs');  const publicKey = fs.readFileSync('es256-public.jwks.json', 'utf8');  jwt.verify(token, publicKey, (err, decoded) => {   if (err) {     console.log('Token verification failed:', err);   } else {     console.log('Token verified successfully:', decoded);   } });
In this example, replace
token
with the JWT you want to verify. For more information, 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 convert ory cookie to session token
c
A message from kapa.ai
To convert an Ory session cookie to a session token, you can use the
/sessions/whoami
endpoint with the
tokenize_as
query parameter. Here's an example of how to do this with a
curl
command:
Copy code
bash curl -X GET \    -H "Cookie: ory_session...=..." \    "https://{project.slug}.<http://projects.oryapis.com/sessions/whoami?tokenize_as=jwt_example_template1|projects.oryapis.com/sessions/whoami?tokenize_as=jwt_example_template1>"
In this example, replace
ory_session...=...
with the actual session cookie and
{project.slug}
with the slug of your project. The
tokenize_as
query parameter is set to
jwt_example_template1
, which should be a valid, configured Ory Session token template. The response from this endpoint will include a
tokenized
property, which is the session token:
Copy code
json {    "tokenized": "{the-jwt}"   }
For more information, 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 get jwt for m2m
c
A message from kapa.ai
To get a JWT for machine-to-machine (M2M) communication, you can use the Client Credentials Grant in OAuth2. This grant type is commonly used in M2M communications, allowing services, applications, or devices to call each other without the context of human users. Here's an example of how to create an OAuth2 client and start the Client Credentials Grant using the Ory CLI: 1. Create an Ory Network project:
Copy code
bash ory create project --name "Ory OAuth2 Example"   project_id="{set to the project ID from output}"
2. Create an OAuth2 client:
Copy code
bash ory create oauth2-client --project "$project_id" \    --name "Client Credentials Demo" \    --grant-type client_credentials
3. Export the ID and secret of the created client:
Copy code
bash client_id="{set to CLIENT ID from output}"   client_secret="{set to CLIENT SECRET from output}"
4. Start the Client Credentials Grant:
Copy code
bash ory perform client-credentials \    --client-id="$client_id" \    --client-secret="$client_secret" \    --project "$project_id"
This will return an access token, which is a JWT that can be used for M2M communication. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/getting-started/ory-network-oauth2#client-credentials-grant).
b
@chilly-king-10285 isn't that an opaque token? And if so how would I convert it to JWT
c
A message from kapa.ai
By default, Ory issues opaque access tokens, which are random strings with a cryptographic signature that have no meaning or structure. However, you can configure Ory to issue JWT access tokens instead. To configure Ory OAuth2 to issue JWT access tokens for a specific client, you'll need to update the client configuration as Ory defaults to opaque tokens. Here's an example of how to do this using the Ory JavaScript SDK:
Copy code
javascript import { Configuration, JsonPatch, 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 patchOAuth2Client(id: string, patches: JsonPatch[]) {    await ory.patchOAuth2Client({    id,    jsonPatch: [    ...patches,    {    op: "replace",    path: "access_token_strategy",    value: "jwt",    },    ],    })   }
In this example,
ory
is an instance of the
OAuth2Api
class. The
patchOAuth2Client
method is used to update the client configuration. The
access_token_strategy
property is set to
"jwt"
, which means that Ory will issue JWT access tokens for this client. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#per-client-configuration).
b
@chilly-king-10285 ok, now I'm getting a presumably encrypted string that represents the jwt. How do I get the jwt out of that? e.g.
Copy code
ory perform client-credentials --client-id="$client_id" --client-secret="$client_secret" --project "$project_id"
ACCESS TOKEN   <long string here>
c
A message from kapa.ai
The string you're seeing as the
ACCESS TOKEN
is the JWT itself. JWTs are composed of three parts: a header, a payload, and a signature. Each part is base64Url encoded, and they are concatenated with periods (
.
) as separators. This results in a long string, which is what you're seeing. You can decode the JWT to view its contents. Here's an example of how to do this in Node.js:
Copy code
javascript const jwt = require('jsonwebtoken'); const token = '<long string here>'; // replace with your JWT  const decoded = jwt.decode(token, { complete: true }); console.log(decoded);
In this example, replace
'<long string here>'
with your JWT. The
jwt.decode
function decodes the JWT and returns its contents. The
{ complete: true }
option tells the function to return the complete decoded token, including the header, payload, and signature. Please note that this only decodes the JWT, it does not verify its signature. To verify the signature, you would need the public key that corresponds to the private key used to sign the JWT. You can get this from the Ory server. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#per-client-configuration) and the [jsonwebtoken documentation](https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken--options).
b
@chilly-king-10285 is there a way to add additional info to that jwt? For example the permissions the client has?
c
A message from kapa.ai
Yes, you can add additional information to the JWT, such as the permissions the client has, by adding custom claims to the access token during consent acceptance. Here's an example of how to do this using the Ory JavaScript 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,
ory
is an instance of the
OAuth2Api
class. The
acceptConsent
function is used to accept a consent request. The
access_token
property of the
session
object is set to an object that includes the custom claims. These claims will be included in the JWT. If you want the custom claim to be added to the top level (instead of a nested level) in the access token, you need to modify the
/oauth2/allowed_top_level_claims
configuration:
Copy code
bash ory patch oauth2-config {project.id} \  --replace "/oauth2/allowed_top_level_claims=[\"some_custom_claim\"]"
In this example, replace
{project.id}
with the ID of your project. The command updates the configuration to allow the
some_custom_claim
claim to be added to the top level of the access token. For more information, you can refer to the [Ory documentation](https://www.ory.sh/docs/oauth2-oidc/jwt-access-token#custom-consent-ui-and-custom-claims-for-jwt-access-token).
b
@chilly-king-10285 how to expand all permissions a user has recursively
c
A message from kapa.ai
To expand all permissions a user has recursively, you can use the Expand API provided by Ory Keto. This API expands a subject set into a tree of subjects, assembling the relationships including the operands as defined in the namespace configuration. Here's an example of how to use the Expand API:
Copy code
bash GET /relation-tuples/expand?namespace=<namespace>&object=<object>&relation=<relation>&max-depth=<max-depth>
In this example, replace
<namespace>
,
<object>
,
<relation>
, and
<max-depth>
with the appropriate values. The
max-depth
parameter can be used to limit the depth of the tree to be returned. If the value is less than 1 or greater than the global max-depth, then the global max-depth will be used instead. The Expand API can be used to list who has access to an object, determine why someone has access to an object, and audit permissions in the system. For more details, you can refer to the [Ory Keto API overview](https://www.ory.sh/docs/keto/concepts/api-overview#expand-subject-sets) and the [Ory Keto REST API reference](https://www.ory.sh/docs/keto/reference/rest-api#getexpand).