<@U04UQ68083H> how should I implement ory sdk to p...
# ory-copilot
i
@chilly-king-10285 how should I implement ory sdk to protect my backend apis? should i use the client sdk or is there any other sdk / method i should use ?
b
A message from kapa.ai
To protect your backend APIs using Ory, you should not use the client SDK. Instead, there are two main approaches you can consider: 1. For self-hosted Ory services: You should use [Ory Oathkeeper](https://github.com/ory/oathkeeper) or a comparable API Gateway to protect access to your APIs. The [Self-hosted API access control documentation](https://www.ory.sh/docs/self-hosted/operations/api-access-control) states that Ory open-source Servers don't come with integrated access control, and leaving the APIs unprotected can lead to severe security risks. 2. For Ory Network: You should use the Admin APIs with an Ory Network API Key for privileged access. The [Ory APIs documentation](https://www.ory.sh/docs/api) mentions that Admin APIs offer privileged access not available to end users and require an Ory Network API Key. To implement this: 1. Create an API Key in the Ory Console as described in the [API Keys section](https://www.ory.sh/docs/getting-started/local-development#api-keys). 2. Use the appropriate SDK for your backend language, which you can find in the [SDK download section](https://www.ory.sh/docs/sdk#download-the-sdk). 3. When initializing the SDK, include your API Key. Here's an example using the Go SDK:
Copy code
go import ory "<http://github.com/ory/client-go|github.com/ory/client-go>"  var client = NewSDK()  // Use this context to access Ory APIs which require an Ory API Key. var oryAuthedContext = context.WithValue(context.Background(), ory.ContextAccessToken, os.Getenv("ORY_API_KEY"))  func NewSDK() *ory.APIClient {   conf := ory.NewConfiguration()   conf.Servers = ory.ServerConfigurations{{     URL: "https://{your-project}.<http://projects.oryapis.com/|projects.oryapis.com/>",   }}    return ory.NewAPIClient(conf) }
This approach ensures that your backend APIs are properly protected and only accessible with the appropriate authorization.
i
@chilly-king-10285 if i dont want to use Oathkeeper with Self Hosted Ory, can I only use the SDKs combined with Keto, or do I absolutely need to use Oathkeeper to interact with and read permissions from Keta ?
b
A message from kapa.ai
You don't absolutely need to use Oathkeeper to interact with and read permissions from Ory Keto (the open-source project that powers Ory Permissions). You can use the Ory Keto SDK directly to perform permission checks and manage relationships in your application. Here's a breakdown of your options: 1. Using Ory Keto SDK: You can use the Ory Keto SDK to interact directly with Keto for permission checks and relationship management. The [Ory Permissions Go SDK documentation](https://www.ory.sh/docs/keto/sdk/go) provides examples of how to use the SDK for both REST and gRPC APIs. 2. Integrating permission checks in your application: The [How to integrate permission checks to your application guide](https://www.ory.sh/docs/keto/guides/simple-access-check-guide#synchronous-authorization-flow) explains how to perform permission checks using Ory Permissions (Keto) directly in your application code. Here's an important note from the guide: "It's crucial that all permission checks are performed using Ory Permissions. This means that before any action is taken, the required permission should be checked to ensure that the action is allowed." To implement this, you would: 1. Authenticate the subject (user) using your preferred method (e.g., Ory Identities). 2. Use the Ory Keto SDK to perform permission checks before allowing actions in your application. For example, using the Go SDK (after setting up authentication):
Copy code
go import (     "context"     ory "<http://github.com/ory/keto-client-go|github.com/ory/keto-client-go>" )  func checkPermission(subject, action, object string) (bool, error) {     client := ory.NewAPIClient(ory.NewConfiguration())     resp, _, err := client.PermissionApi.CheckPermission(context.Background()).         Namespace("your-namespace").         Object(object).         Relation(action).         Subject(subject).         Execute()     if err != nil {         return false, err     }     return resp.Allowed, nil }
This approach allows you to use Keto for permission checks without Oathkeeper, giving you more flexibility in your architecture. Remember to secure your Keto instance properly, as mentioned in the [Keto installation documentation](https://www.ory.sh/docs/keto/install): "The APIs of Ory open-source Servers don't come with integrated access control. This means that all requests sent to their APIs are considered authenticated, authorized, and will be executed. Leaving the APIs in this state can lead to severe security risks." While Oathkeeper is recommended for API access control, you can implement your own access control layer using the Keto SDK if you prefer not to use Oathkeeper.
i
I'm building a NodeJS backend, so I would need to call the APIs to check for user identity on requests, but also permissions, etc... How could I do that with NodeJS as the SDKs from the url you just sent are meant for Golang ?
@chilly-king-10285 I'm building a NodeJS backend, so I would need to call the APIs to check for user identity on requests, but also permissions, etc... How could I do that with NodeJS as the SDKs from the url you just sent are meant for Golang ?
b
A message from kapa.ai
I apologize for the confusion in my previous response. You're right that the Go SDK examples aren't suitable for your NodeJS backend. Let me provide you with the correct information for implementing Ory SDK in a NodeJS environment to check user identity and permissions. For a NodeJS backend, you can use the Ory JavaScript SDK. Here's how you can implement it: 1. First, install the Ory SDK:
Copy code
npm install @ory/client
2. Then, you can set up the SDK client in your NodeJS application:
Copy code
javascript const { Configuration, FrontendApi, PermissionApi } = require("@ory/client")  const ory = new FrontendApi(   new Configuration({     basePath: "https://{YOUR-PROJECT-SLUG}.<http://projects.oryapis.com|projects.oryapis.com>",     baseOptions: {       withCredentials: true,     },   }), )  const permissionApi = new PermissionApi(   new Configuration({     basePath: "https://{YOUR-PROJECT-SLUG}.<http://projects.oryapis.com|projects.oryapis.com>",   }), )
3. To check user identity (session), you can use the
toSession
method:
Copy code
javascript const express = require("express") const app = express()  app.get("/protected-route", async function (req, res) {   try {     const session = await ory.toSession({       cookie: req.header("cookie"),     })     // User is authenticated, proceed with your logic     res.json({ message: "Authenticated", user: session.data.identity })   } catch (error) {     // User is not authenticated     res.status(401).json({ message: "Unauthorized" })   } })
This example is based on the [Express.js integration guide](https://www.ory.sh/docs/getting-started/integrate-auth/expressjs#require-login-to-access-the-home-page). 4. To check permissions using Ory Permissions (Keto), you can use the
checkPermission
method:
Copy code
javascript app.get("/resource/:id", async function (req, res) {   try {     const session = await ory.toSession({       cookie: req.header("cookie"),     })          const permission = await permissionApi.checkPermission({       namespace: "your-namespace",       object: req.params.id,       relation: "read",       subjectId: session.data.identity.id,     })      if (permission.data.allowed) {       // User has permission, proceed with your logic       res.json({ message: "Access granted" })     } else {       res.status(403).json({ message: "Access denied" })     }   } catch (error) {     res.status(401).json({ message: "Unauthorized" })   } })
This example combines session checking and permission checking, as described in the [Synchronous authorization flow guide](https://www.ory.sh/docs/keto/guides/simple-access-check-guide#synchronous-authorization-flow). Remember to replace
{YOUR-PROJECT-SLUG}
with your actual Ory project slug, and adjust the namespace, object, and relation according to your permission model. By implementing these methods, you can protect your NodeJS backend APIs by checking both user identity and permissions using the Ory SDK.
i
@chilly-king-10285 is it really better to use Ory SDKs ? are those actively maintained ? Or could it be better to read the implementation docs from https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration and https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration and implement the auth checks i need by myself from scratch ? what do you think ?
b
A message from kapa.ai
Based on the information provided in the knowledge sources, I can offer the following perspective on your question: 1. Ory SDKs vs. Custom Implementation: Ory provides SDKs for various programming languages, which can simplify the integration process. However, Ory also offers detailed documentation for implementing custom user interfaces and integrations. The [Custom UI Overview](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-overview) states that "Ory is designed to allow you to use custom user interfaces (UI) for browser and native applications thanks to simple-to-use headless API flows." This suggests that while SDKs are available, Ory's architecture supports custom implementations as well. 2. SDK Maintenance: The knowledge sources don't provide specific information about the active maintenance of Ory SDKs. However, Ory does offer [SDK quickstarts](https://www.ory.sh/docs/quickstart/sdks) for various services, indicating that SDKs are a supported integration method. 3. Custom Implementation: The documents you mentioned, [Basic Integration](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration) and [Advanced Integration](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration), provide detailed guidance on implementing custom UIs and integrations with Ory services. These resources can be valuable if you decide to implement auth checks from scratch. 4. Recommendation: The choice between using SDKs or implementing from scratch depends on your specific needs and resources. Here are some factors to consider: - If you need quick integration and want to leverage pre-built functions, using the SDKs might be more efficient. - If you require fine-grained control over the implementation or have specific requirements that the SDKs don't cover, a custom implementation using the API directly might be more suitable. - Consider your team's expertise and the time you can allocate to the integration. SDKs can often reduce development time, while custom implementations might require more effort but offer more flexibility. Ultimately, both approaches are valid and supported by Ory. You might want to start with the SDK for rapid prototyping and then gradually customize as needed, or go for a custom implementation if you have specific requirements from the beginning. Remember, regardless of the approach you choose, it's crucial to follow Ory's security best practices and keep your implementation up-to-date with the latest Ory updates and security recommendations.
i
@chilly-king-10285 isn't it kind of bad for performances to have main app data / ressources separated from rbac and user account ressources ( from kratos and keto ) ?
b
A message from kapa.ai
Your question raises an important point about system architecture and performance. Let's examine this based on the information provided in the Ory documentation: 1. Separation of Concerns: Ory's architecture is designed with a separation of concerns in mind. As mentioned in the [Ory Network Components documentation](https://www.ory.sh/docs/welcome#components), Ory separates identity management (Kratos), permissions (Keto), and OAuth2/OpenID Connect (Hydra) into distinct services. This separation allows for better scalability, maintainability, and security. 2. Performance Considerations: While separating resources might seem like it could impact performance, Ory has designed its systems to be high-performance. The [Ory Keto documentation](https://www.ory.sh/docs/keto/guides/simple-access-check-guide) describes it as a "low-latency, high-performance, relationship-based authorization system." 3. Global Distribution: Ory Network is designed for global distribution and low latency. According to the [Personal Data Location documentation](https://www.ory.sh/docs/security-compliance/personal-data-location), "Ory Network is globally distributed for maximum resilience and minimum latency." This architecture helps mitigate potential performance issues from separated resources. 4. Data Separation for Compliance: The separation of personal data (managed by Kratos) from operational data (like permissions in Keto) is actually beneficial for compliance with regulations like GDPR. The [Personal Data Location documentation](https://www.ory.sh/docs/security-compliance/personal-data-location) states, "Ory Network solves this by separating personal data from operational data." 5. Efficient Integration: Ory provides SDKs and APIs that allow for efficient integration of these separated services. As shown in the [NodeJS integration example](https://www.ory.sh/docs/getting-started/integrate-auth/expressjs#require-login-to-access-the-home-page), you can perform identity checks and permission checks in a single request flow. In conclusion, while separating resources might seem counterintuitive for performance, Ory's architecture is designed to provide high performance, global scalability, and regulatory compliance. The potential slight overhead of separate API calls is often outweighed by the benefits of this architecture, including better security, scalability, and compliance. However, if you have specific high-performance requirements, you might want to conduct performance testing in your specific use case to ensure it meets your needs.