<@U04UQ68083H> how can I integrate kratos in fasta...
# ory-copilot
l
@chilly-king-10285 how can I integrate kratos in fastapi?
c
A message from kapa.ai
Hmm, I don't know enough to give you a confident answer yet. The knowledge sources provided do not contain specific information on integrating Ory Kratos with FastAPI. However, Ory Kratos can be integrated with various applications and APIs. You might find it helpful to review the [Ory documentation](https://www.ory.sh/docs/) for more information.
l
@chilly-king-10285 how can i use kratos in python?
c
A message from kapa.ai
You can use Ory Kratos in Python by using the Ory Python SDK. Here are the steps to set it up: 1. Set up a new Python project:
Copy code
mkdir myproject       cd myproject
2. Install the Ory Python SDK: You can install it directly from the repository using pip:
Copy code
pip install git+<https://github.com/ory/sdk.git>
You may need to run
pip
with root permission:
sudo pip install git+<https://github.com/ory/sdk.git>
. Alternatively, you can install via Setuptools:
Copy code
python setup.py install --user
Or use
sudo python setup.py install
to install the package for all users. 3. Import the package:
Copy code
import ory_client
You can find more examples of SDK usage in the auto-generated documentation for [
ory-client
](https://github.com/ory/sdk/blob/master/clients/client/python/README.md). Please note that the Ory SDK uses automated code generation by [
openapi-generator
](https://github.com/OpenAPITools/openapi-generator).
openapi-generator
can make changes to the generated code with each new version, which breaks backwards compatibility in some cases. As a result, Ory SDK may not be compatible with previous versions. For more detailed information, you can refer to the [Ory Python SDK documentation](https://www.ory.sh/docs/keto/sdk/python). Please note that the specific usage of the SDK will depend on your application's requirements and the specific features of Ory Kratos that you wish to use. Sources: - [Ory Python SDK documentation](https://www.ory.sh/docs/keto/sdk/python) - [Ory Kratos SDK Overview](https://www.ory.sh/docs/kratos/sdk/overview)
l
@chilly-king-10285 i am using ory in react, i want to get cookie upon login, how can i?
c
A message from kapa.ai
When a user successfully logs in using Ory in a React application, Ory issues a session cookie. This cookie can be used to authenticate subsequent requests. Here's an example of how you can get the session cookie in a React application:
Copy code
jsx import React, { useEffect, useState } from "react"   import { FrontendApi, Configuration, Session, Identity } from "@ory/client"    const basePath = process.env.REACT_APP_ORY_URL || "<http://localhost:4000>"   const ory = new FrontendApi(    new Configuration({    basePath,    baseOptions: {    withCredentials: true,    },    }),   )    function App() {    const [session, setSession] = useState<Session | undefined>()     useEffect(() => {    ory    .toSession()    .then(({ data }) => {    setSession(data)    })    .catch((err) => {    console.error(err)    window.location.replace(`${basePath}/ui/login`)    })    }, [])     if (!session) {    return <h1>Loading...</h1>    }     return (    <div className="App">    // Your application code here  </div>    )   }
In this example, the
ory.toSession()
method is used to get the session data, which includes the session cookie. The
withCredentials: true
option in the SDK configuration ensures that the cookie is included in the request. Please note that the specific usage of the SDK and the handling of the session cookie will depend on your application's requirements and the specific features of Ory that you wish to use. Sources: - [Integrate authentication into React](https://www.ory.sh/docs/getting-started/integrate-auth/react#require-login-to-access-the-app-page) - [Using Ory Session Cookie](https://www.ory.sh/docs/kratos/session-management/overview#using-ory-session-cookie)
l
@chilly-king-10285 where exactly can I get the cookie?
c
A message from kapa.ai
When a user logs in successfully, Ory issues an Ory Session Cookie. This cookie is automatically stored in the user's browser and is sent with every subsequent request to the server. In a browser-based application, you don't typically need to manually retrieve the cookie. Instead, you use the Ory SDK's
toSession()
method to interact with the session data. This method automatically includes the session cookie in the request when the
withCredentials: true
option is set in the SDK configuration. Here's an example of how you can use the
toSession()
method in a React application:
Copy code
jsx import { Configuration, FrontendApi, Session } from "@ory/client"   import { useEffect, useState } from "react"    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(() => {    frontend    // the cookie is automatically sent with the request    .toSession()    .then(({ data: session }) => {    setSession(session)    })    .catch((error) => {    // The session could not be fetched    // This might occur if the current session has expired    })    }, [])     return session ? (    // Your application code here  ) : (    <div>Loading session data...</div>    )   }
In this example, the
toSession()
method is used to get the session data, which includes the session cookie. The
withCredentials: true
option in the SDK configuration ensures that the cookie is included in the request. Please note that the specific usage of the SDK and the handling of the session cookie will depend on your application's requirements and the specific features of Ory that you wish to use. Sources: - [Using Ory Session Cookie](https://www.ory.sh/docs/kratos/session-management/overview#using-ory-session-cookie) - [Session Checks](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks)
l
but i need the cookie @chilly-king-10285
c
A message from kapa.ai
When a user logs in successfully, Ory responds with a
Set-Cookie
HTTP header that contains the Ory Session Cookie. This cookie is automatically stored in the user's browser and is sent with every subsequent request to the server. Here's an example of the HTTP response headers you would see after a successful login:
Copy code
HTTP/1.1 303 See Other   Cache-Control: 0   Location: <http://127.0.0.1:4455/>   Set-Cookie: ory_kratos_session=MTU5OTE2ODc2N3xEdi1CQkFFQ180SUFBUkFCRUFBQVJfLUNBQUVHYzNSeWFXNW5EQThBRFhObGMzTnBiMjVmZEc5clpXNEdjM1J5YVc1bkRDSUFJR055VlROMGRteHhSakJrUzBkbmRUUjBlVFY1V0RCRWFVTnJXVmR6V25oaHx2DICsB6IMbaHSQwnYITUZqr7Qx7CxUlnaneJWH495wQ==; Path=/; Expires=Fri, 04 Sep 2020 21:32:47 GMT; Max-Age=86400; HttpOnly; SameSite=Lax   Vary: Cookie   Date: Thu, 03 Sep 2020 21:32:47 GMT   Content-Length: 0
In this example, the
Set-Cookie
header contains the Ory Session Cookie (
ory_kratos_session
). However, in a typical web application, you don't usually need to manually retrieve this cookie. The browser automatically handles storing and sending the cookie with each request. If you need to access the cookie in your application, you would typically do so through the document's
cookie
property in JavaScript. Please note that due to security restrictions, JavaScript can only access cookies that have been set with the
HttpOnly
flag set to
false
. The Ory Session Cookie is set with
HttpOnly
set to
true
to prevent access from JavaScript and mitigate the risk of cross-site scripting (XSS) attacks. Sources: - [Successful Login](https://www.ory.sh/docs/kratos/self-service/flows/user-login#successful-login) - [Successful Registration](https://www.ory.sh/docs/kratos/self-service/flows/user-registration#server-side-browser-clients)
l
@chilly-king-10285 how can i retreive authorization bearer token from session?
c
A message from kapa.ai
In Ory, when a user authenticates, they receive a session. This session can be represented in two formats: an Ory Session Cookie or an Ory Session Token. The Ory Session Token is equivalent to a session cookie, but it can be sent in the HTTP Authorization Header:
Copy code
Authorization: bearer ${session-token}
The session token is only issued for API flows, not for Browser flows. This token is typically used when the interaction is performed by a client other than a web browser, for example, a native mobile app. To retrieve the session token, you can make a call to the
/session/whoami
endpoint. Here's an example using curl:
Copy code
bash curl -X GET \  -H 'Content-Type: application/json' \  -H 'Accept: application/json' \  -H 'Authorization: Bearer <your-session-token>' \  https://{project.slug}.<http://projects.oryapis.com/sessions/whoami|projects.oryapis.com/sessions/whoami>
In this example, replace
<your-session-token>
with your actual session token. Please note that for security reasons, you can't break the isolation between cookies and session tokens. Sources: - [Session Management Overview](https://www.ory.sh/docs/kratos/session-management/overview) - [Session Checks](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
@chilly-king-10285 and from where i will get the token?
c
A message from kapa.ai
The Ory Session Token is issued by the Ory system when a user authenticates, specifically for non-browser clients such as a native mobile app. When a user logs in or registers, the session token is set as part of the response. This token is equivalent to a session cookie and can be sent in the HTTP Authorization Header. Here's an example of how you might retrieve the session token in a non-browser client:
Copy code
bash curl -X POST \  -H 'Content-Type: application/json' \  -H 'Accept: application/json' \  -d '{    "password": "<user-password>",    "identifier": "<user-identifier>"  }' \  https://<your-ory-server>/self-service/login/api
In this example, replace
<user-password>
with the user's password,
<user-identifier>
with the user's identifier (such as their username or email), and
<your-ory-server>
with the address of your Ory server. The response to this request will include the session token if the login was successful. Please note that the specific way you retrieve the session token may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Session Management Overview](https://www.ory.sh/docs/kratos/session-management/overview) - [Successful Login](https://www.ory.sh/docs/kratos/self-service/flows/user-login#successful-login) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
@chilly-king-10285 if i want to display credentials/headers in react spa, how can i?
c
A message from kapa.ai
In a React Single Page Application (SPA), you can display request headers or credentials by making a request to your server and then displaying the response. Here's an example of how you might do this using the
fetch
API:
Copy code
jsx import React, { useEffect, useState } from 'react';  function App() {   const [headers, setHeaders] = useState(null);    useEffect(() => {     fetch('<https://your-api-endpoint>', {       credentials: 'include', // This includes credentials in the request     })       .then(response => {         setHeaders(response.headers);       })       .catch(error => console.error(error));   }, []);    return (     <div>       {headers &&          Object.entries(headers).map(([key, value]) => (           <div key={key}>             <strong>{key}:</strong> {value}           </div>         ))       }     </div>   ); }  export default App;
In this example, replace
'<https://your-api-endpoint>'
with the URL of your API endpoint. The
fetch
function makes a request to the server, and the
credentials: 'include'
option ensures that credentials (such as cookies) are included in the request. The response headers are then stored in the
headers
state variable and displayed in the component. Please note that due to security restrictions, not all headers may be accessible through the
headers
object. Also, the specific way you display headers or credentials may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Accessing APIs from client-side JavaScript / AJAX](https://www.ory.sh/docs/troubleshooting/csrf#accessing-apis-from-client-side-javascript--ajax) - [Single-page application (SPA)](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#single-page-application-spa)
l
@chilly-king-10285 which api should i hit to get and display headers/credentials of session?
c
A message from kapa.ai
To get and display the headers/credentials of a session in Ory, you can make a request to the
/sessions/whoami
endpoint. This endpoint returns the session's identity in the response body. Here's an example of how you might do this in a React application:
Copy code
jsx import React, { useEffect, useState } from 'react';  function App() {   const [session, setSession] = useState(null);    useEffect(() => {     fetch('<https://your-ory-server/sessions/whoami>', {       credentials: 'include', // This includes credentials in the request     })       .then(response => response.json())       .then(data => {         setSession(data);       })       .catch(error => console.error(error));   }, []);    return (     <div>       {session &&          Object.entries(session).map(([key, value]) => (           <div key={key}>             <strong>{key}:</strong> {JSON.stringify(value)}           </div>         ))       }     </div>   ); }  export default App;
In this example, replace
'<https://your-ory-server/sessions/whoami>'
with the URL of your Ory server and the
/sessions/whoami
endpoint. The
fetch
function makes a request to the server, and the
credentials: 'include'
option ensures that credentials (such as cookies) are included in the request. The session data is then stored in the
session
state variable and displayed in the component. Please note that the specific way you display the session data may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Session Checks](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
@chilly-king-10285
c
Sorry @lemon-student-13425, I'm not sure what you mean. Please try again. 👋
l
@chilly-king-10285 if i am taking data from another app, which has email of user stored with it and i want to retreive that data in my app but first i want to authenticate if the user is authenticated with ory or not. how can i do so
c
A message from kapa.ai
To authenticate a user with Ory and retrieve data from another app, you can follow these steps: 1. Authenticate the user with Ory: You can use the Ory SDK or directly interact with the Ory APIs to authenticate the user. If the user is authenticated successfully, Ory will issue a session token or a session cookie. 2. Check the user's session: You can make a request to the
/sessions/whoami
endpoint to check if the user's session is active. If the session is active, the endpoint will return the session's identity. Here's an example of how you might do this in a React application:
Copy code
jsx import React, { useEffect, useState } from 'react';  function App() {   const [session, setSession] = useState(null);    useEffect(() => {     fetch('<https://your-ory-server/sessions/whoami>', {       credentials: 'include', // This includes credentials in the request     })       .then(response => response.json())       .then(data => {         setSession(data);       })       .catch(error => console.error(error));   }, []);    // If the session is active, the user is authenticated   const isAuthenticated = session !== null;    // Your code to retrieve data from the other app goes here   // You can use the `isAuthenticated` variable to check if the user is authenticated    return <div>{/* Your application code here */}</div>; }  export default App;
In this example, replace
'<https://your-ory-server/sessions/whoami>'
with the URL of your Ory server and the
/sessions/whoami
endpoint. 3. Retrieve data from the other app: Once you have confirmed that the user is authenticated, you can make a request to the other app to retrieve the user's data. The specifics of this step will depend on how the other app's API is designed. Please note that the specific way you authenticate the user and retrieve data from the other app may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Session Checks](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
how would i send the session to another app where that app can check user session @chilly-king-10285
c
A message from kapa.ai
To send the session to another app, you would typically include the session token in the request to the other app. The other app can then use this token to verify the session with Ory. Here's an example of how you might do this: 1. Retrieve the session token: When a user logs in, Ory issues a session token. This token can be retrieved from the response to the login request. 2. Send the session token to the other app: Include the session token in the request to the other app. This could be done as a header, a query parameter, or part of the request body, depending on the other app's API.
Copy code
jsx fetch('<https://other-app.com/api>', {   headers: {     'Authorization': `Bearer ${sessionToken}`   } }) .then(response => response.json()) .then(data => {   // Handle the response from the other app }) .catch(error => console.error(error));
In this example, replace
'<https://other-app.com/api>'
with the URL of the other app's API, and
sessionToken
with the actual session token. 3. Verify the session token in the other app: The other app can verify the session token by making a request to the
/sessions/whoami
endpoint on the Ory server.
Copy code
bash curl -H "Authorization: Bearer {your-session-token}" \  "https://{project.slug}.<http://projects.oryapis.com/sessions/whoami|projects.oryapis.com/sessions/whoami>"
In this example, replace
{your-session-token}
with the actual session token, and
{project.slug}.<http://projects.oryapis.com|projects.oryapis.com>
with the address of your Ory server. Please note that the specific way you send the session to the other app and verify it may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Session Management Overview](https://www.ory.sh/docs/kratos/session-management/overview) - [Session Checks](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
@chilly-king-10285 i cannot find session token in response of login
c
A message from kapa.ai
The session token is included in the response when the
session
after hook is enabled. If you're not seeing the session token in the response, it's possible that this hook is not enabled. Here's an example of a successful login response that includes the session token:
Copy code
json {   "session_token": "oFZzgLpsacUpUy2cvQPtrGa2046WcXCR",   "session": {     "id": "8f660ce3-69ec-4aeb-9fda-f9230dc3243f",     "active": true,     "expires_at": "2020-08-25T13:42:15.7411522Z",     "authenticated_at": "2020-08-24T13:42:15.7411522Z",     "issued_at": "2020-08-24T13:42:15.7412042Z",     "identity": {       "id": "bf32596a-f853-47c4-91e6-a3f41cf4949d",       "schema_id": "default",       "schema_url": "<https://playground.projects.oryapis.com/schemas/default>",       "traits": {         "email": "[[email protected]](<https://www.ory.sh/cdn-cgi/l/email-protection>)",         "name": {           "last": "User",           "first": "API"         }       }     }   } }
In this example, the
session_token
field contains the session token. If you're not seeing the session token in the response, you may need to check your Ory configuration to ensure that the
session
after hook is enabled. Sources: - [Successful Login](https://www.ory.sh/docs/kratos/self-service/flows/user-login#successful-login) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
@chilly-king-10285 how can i enable session hook after login?
c
A message from kapa.ai
To enable the
session
hook after login, you need to modify your Ory configuration. This can be done by adding the
session
hook to the
after
login flow in your configuration file. Here's an example of how you might do this:
Copy code
yaml selfservice:   flows:     login:       after:         password:           hooks:             - hook: session         oidc:           hooks:             - hook: session
In this example, the
session
hook is added to the
after
login flow for both the
password
and
oidc
methods. This means that a session will be issued immediately after a successful login. Please note that the specific way you modify your Ory configuration may vary depending on your setup and the specific features of Ory that you are using. Sources: - [Successful Registration](https://www.ory.sh/docs/kratos/self-service/flows/user-registration#successful-registration) - [Ory Configuration](https://www.ory.sh/docs/kratos/configuration)
l
@chilly-king-10285 how can i get session token on whoami?
c
A message from kapa.ai
The
/sessions/whoami
endpoint in Ory is used to check who the current HTTP session belongs to. It uses the HTTP headers in the GET request to determine who is authenticated. However, this endpoint does not directly provide the session token. The session token is typically provided when a user logs in or registers via the API flows. It's included in the response body if the
session
hook is configured as a post-registration or post-login hook. If you want to use the session token in a non-browser application (e.g., mobile app), you need to include the session token in the request to the
/sessions/whoami
endpoint. Here's an example:
Copy code
bash curl -H "Authorization: Bearer {{your-session-token}}" \  "https://{{project.slug}}.<http://projects.oryapis.com/sessions/whoami|projects.oryapis.com/sessions/whoami>"
In this example, replace
{{your-session-token}}
with the actual session token, and
{{project.slug}}.<http://projects.oryapis.com|projects.oryapis.com>
with the address of your Ory server. Please note that the session token is equivalent to a session cookie, but it can be sent in the HTTP Authorization Header. The session token is only issued for API flows, not for Browser flows. Sources: - [Ory API Reference](https://www.ory.sh/docs/reference/api) - [Session Management Overview](https://www.ory.sh/docs/kratos/session-management/overview) - [Session Checks](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-basic-integration#session-checks)
l
@chilly-king-10285 how can i get session token after login in react spa
c
A message from kapa.ai
In a React Single Page Application (SPA), when a user logs in through the browser-based login flow, Ory issues a Session Cookie, not a Session Token. The Session Cookie is automatically stored in the user's browser and sent with each subsequent request. To check the user's session status, you can make a request to the
/sessions/whoami
endpoint. Here's an example of how you might do this in a React application:
Copy code
jsx import { Configuration, FrontendApi, Session } from "@ory/client"   import { useEffect, useState } from "react"      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(() => {    frontend    // the cookie is automatically sent with the request    .toSession()    .then(({ data: session }) => {    setSession(session)    })    .catch((error) => {    // The session could not be fetched    // This might occur if the current session has expired    })    }, [])       return session ? (    <table>    <tr>    <th>Session ID</th>    <th>Expires at</th>    <th>Authenticated at</th>    </tr>    <tr id={session.id}>    <td>{session.id}</td>    <td>{session.expires_at || ""}</td>    <td>{session.authenticated_at || ""}</td>    </tr>    </table>    ) : (    <div>Loading session data...</div>    )   }
In this example, the
toSession
method is used to check the user's session status. If the session is active, the session data is stored in the
session
state variable and displayed in the component. Please note that the session token is typically used when the interaction is performed by a client other than a web browser, for example, a native mobile app. Sources: - [Using Ory Session Cookie](https://www.ory.sh/docs/kratos/session-management/overview#using-ory-session-cookie) - [Check session status](https://www.ory.sh/docs/identities/sign-in/check-session-token-cookie-api)
l
@chilly-king-10285 i need one of cookie or session_token to send to another app for session verification. how can i do so in react spa?
c
A message from kapa.ai
In a React Single Page Application (SPA), when a user logs in through the browser-based login flow, Ory issues a Session Cookie. This cookie is automatically stored in the user's browser and sent with each subsequent request. To send the session cookie to another app, you can include it in the request to the other app. However, due to security restrictions, JavaScript cannot directly access the HTTP cookies. Instead, the browser automatically includes the cookies in the request when the
credentials: 'include'
option is set in the fetch API. Here's an example of how you might send a request to another app with the session cookie included:
Copy code
jsx fetch('<https://other-app.com/api>', {   credentials: 'include', // This includes cookies in the request }) .then(response => response.json()) .then(data => {   // Handle the response from the other app }) .catch(error => console.error(error));
In this example, replace
'<https://other-app.com/api>'
with the URL of the other app's API. The other app can then verify the session by making a request to the
/sessions/whoami
endpoint on the Ory server with the session cookie included. Please note that the specific way you send the session cookie to the other app and verify it may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Using Ory Session Cookie](https://www.ory.sh/docs/kratos/session-management/overview#using-ory-session-cookie) - [Check session status](https://www.ory.sh/docs/identities/sign-in/check-session-token-cookie-api)
l
@chilly-king-10285 i want to move from cookies to session_token in my react spa, how can i?
c
A message from kapa.ai
To move from cookies to session tokens in your React SPA, you would need to modify your authentication flow to use the Ory API flows instead of the browser-based flows. The API flows are designed for clients other than web browsers, such as native mobile apps, and they use session tokens instead of cookies. Here's an example of how you might do this: 1. Authenticate the user with Ory: You can use the Ory SDK or directly interact with the Ory APIs to authenticate the user. If the user is authenticated successfully, Ory will issue a session token.
Copy code
jsx import { Configuration, PublicApi, Session } from "@ory/client";  const ory = new PublicApi(   new Configuration({     basePath: "<http://localhost:4000>", // Use your local Ory URL   }) );  async function authenticateUser() {   const { data: flow } = await ory.initializeSelfServiceLoginWithoutBrowserForAPIOnlyFlow();   const { data: session } = await ory.submitSelfServiceLoginFlow(flow.id, {     password_identifier: "<mailto:user@example.com|user@example.com>",     password: "password",   });    return session.session_token; }
In this example, replace
"<http://localhost:4000>"
with the URL of your Ory server, and
"<mailto:user@example.com|user@example.com>"
and
"password"
with the user's actual credentials. 2. Store the session token: Once you have the session token, you can store it in a secure location, such as the browser's local storage.
Copy code
jsx localStorage.setItem("session_token", sessionToken);
3. Include the session token in requests: When making requests to the Ory server or to your own API, include the session token in the
Authorization
header.
Copy code
jsx fetch('<https://your-api-endpoint>', {   headers: {     'Authorization': `Bearer ${sessionToken}`   } }) .then(response => response.json()) .then(data => {   // Handle the response }) .catch(error => console.error(error));
In this example, replace
'<https://your-api-endpoint>'
with the URL of your API endpoint, and
sessionToken
with the actual session token. Please note that the specific way you authenticate the user, store the session token, and include it in requests may vary depending on your application's requirements and the specific features of Ory that you are using. Sources: - [Ory Session Tokens](https://www.ory.sh/docs/security-compliance/token-formats#ory-session-tokens) - [Ory API Reference](https://www.ory.sh/docs/reference/api)
l
@chilly-king-10285 i am sending withCredentials:true to a cross site app which takes cookie from it and verifies session and send data accoordingly, but the coookie is not sent. what should i do?
c
A message from kapa.ai
When making cross-origin requests with AJAX or fetch in a Single Page Application (SPA), cookies are not included by default. To include cookies in the request, you need to set
credentials: 'include'
in your fetch request or
withCredentials: true
in your AJAX request. However, for the cookies to be sent and received properly in a cross-origin scenario, both the client and the server need to be correctly configured: 1. Client-side: Ensure that you're setting
credentials: 'include'
in your fetch request or
withCredentials: true
in your AJAX request.
Copy code
javascript fetch('<https://your-api-endpoint>', {   credentials: 'include', // This includes cookies in the request })
2. Server-side: The server needs to respond with the appropriate CORS headers. Specifically, the
Access-Control-Allow-Credentials
header needs to be set to
true
, and the
Access-Control-Allow-Origin
header cannot be
*
but must specify the exact origin of the client. If you're using Ory, you can configure this in the Ory JavaScript / TypeScript SDK:
Copy code
javascript import { FrontendApi, Configuration } from "@ory/client"      const ory = new FrontendApi(    new Configuration({    basePath,    baseOptions: {    // Ensures we send cookies in the CORS requests.    withCredentials: true,    },    }),   )
If you're still having issues, check the following: - Same top-level domain: The requests are allowed only if the server at
<http://api.example.org|api.example.org>
responds with the appropriate CORS headers and the JavaScript XHR request is made with
credentials: 'include'
. - Local development: If you're developing locally, make sure that all of your requests are sent to
localhost
and not
127.0.0.1
. Cookies set on
localhost
will not be sent in requests to
127.0.0.1
and vice versa. Sources: - [Accessing APIs from client-side JavaScript / AJAX](https://www.ory.sh/docs/troubleshooting/csrf#accessing-apis-from-client-side-javascript--ajax) - [Same top-level domain](https://www.ory.sh/docs/security-model#same-top-level-domain) - [Local development](https://www.ory.sh/docs/getting-started/local-development#limitations)
l
@chilly-king-10285 how can i reset production db on ubuntu?
c
A message from kapa.ai
To reset the production database on Ubuntu, you can use the
kratos cleanup sql
command provided by Ory Kratos. This command cleans up the SQL database from expired flows and sessions. Here's an example of how you might use this command:
Copy code
bash kratos cleanup sql <database-url> [flags]
In this example, replace
<database-url>
with the URL of your database. Please note that you should create a backup of your database before running this command, as it will remove data from the database. Here are some options you can use with this command:
Copy code
bash  -c, --config strings Path to one or more .json, .yaml, .yml, .toml config files. Values are loaded in the order provided, meaning that the last config file overwrites values from the previous config file.    -b, --database.cleanup.batch_size int Set the number of records to be cleaned per run (default 100)    --database.cleanup.sleep.tables duration How long to wait between each table cleanup (default 1m0s)    -h, --help help for sql    --keep-last duration Don't remove records younger than    -e, --read-from-env If set, reads the database connection string from the environment variable DSN or config file key dsn. (default true)
For more information, see the [kratos cleanup sql](https://www.ory.sh/docs/kratos/cli/kratos-cleanup-sql#kratos-cleanup-sql) documentation.
l
@chilly-king-10285 is it going to truncate my db?
c
A message from kapa.ai
The
kratos cleanup sql
command does not truncate your database. Instead, it cleans up expired flows and sessions from your SQL database. This means it will only remove data that is no longer needed, such as expired user sessions and authentication flows. However, it's important to note that you should always create a backup of your database before running this command, to prevent any accidental data loss. For more information, see the [kratos cleanup sql](https://www.ory.sh/docs/kratos/cli/kratos-cleanup-sql#kratos-cleanup-sql) documentation.
l
@chilly-king-10285 how can i truncate all my identity and related tables?
c
A message from kapa.ai
To truncate all your identity and related tables, you would typically use SQL commands. The exact commands depend on the SQL database you are using. Here's an example of how you might do this in PostgreSQL:
Copy code
sql TRUNCATE TABLE identities CASCADE; TRUNCATE TABLE identity_verifiable_addresses CASCADE; TRUNCATE TABLE identity_recovery_addresses CASCADE;
In this example, the
TRUNCATE TABLE
command is used to remove all rows from the specified tables, and the
CASCADE
option is used to automatically truncate all tables that have foreign key references to the specified tables. Please note that this operation will permanently delete all data from these tables. You should create a backup of your database before running these commands to prevent any accidental data loss. Also, be aware that these commands should be executed by a user with sufficient privileges to truncate tables. For more information, see the [PostgreSQL TRUNCATE TABLE](https://www.postgresql.org/docs/current/sql-truncate.html) documentation.
l
@chilly-king-10285 i want to store array of objects in traits. what should my identity json look like?
c
A message from kapa.ai
To store an array of objects in traits, you would need to define the traits property as an array of objects in your identity JSON schema. Here's an example of how you might do this:
Copy code
json {   "$schema": "<http://json-schema.org/draft-07/schema#>",   "type": "object",   "properties": {     "traits": {       "type": "array",       "items": {         "type": "object",         "properties": {           "property1": {             "type": "string"           },           "property2": {             "type": "string"           }         }       }     }   } }
In this example, the
traits
property is defined as an array of objects, each of which has two properties:
property1
and
property2
. You can replace
property1
and
property2
with the actual properties you want to store in the objects. For more information, see the [Customize identity schemas](https://www.ory.sh/docs/kratos/manage-identities/customize-identity-schema#writing-your-first-custom-identity-schema) documentation.
l
@chilly-king-10285 how can i reset and truncate tables on kratos that is on my local using docker with sqlite
c
A message from kapa.ai
To reset and truncate tables in Ory Kratos that is running locally with SQLite using Docker, you would need to delete the SQLite database file and then run the migrations again. Here's how you can do it: 1. Stop the Ory Kratos Docker container:
Copy code
bash docker-compose -f quickstart.yml down
2. Delete the SQLite database file: The SQLite database is stored in a file. This file is usually located in the directory where you started the Ory Kratos Docker container. The exact location depends on your Docker volume configuration. Once you find the file, you can delete it using the
rm
command:
Copy code
bash rm /path/to/your/database.sqlite
Replace
/path/to/your/database.sqlite
with the actual path to your SQLite database file. 3. Start the Ory Kratos Docker container and run the migrations:
Copy code
bash docker-compose -f quickstart.yml up -d docker run -e DSN="sqlite:///path/to/your/database.sqlite" oryd/kratos:<version> migrate sql -e
Replace
/path/to/your/database.sqlite
with the path where you want the new SQLite database file to be created, and replace
<version>
with the version of Ory Kratos you are using. Please note that this operation will permanently delete all data from your SQLite database. You should create a backup of your database before running these commands to prevent any accidental data loss. For more information, see the [Ory Kratos Docker](https://www.ory.sh/docs/kratos/guides/docker) and [kratos cleanup sql](https://www.ory.sh/docs/kratos/cli/kratos-cleanup-sql#kratos-cleanup-sql) documentation.
l
@chilly-king-10285 what if dsn is memory
c
A message from kapa.ai
If your Data Source Name (DSN) is set to
memory
, it means that Ory Kratos is using an in-memory SQLite database. This type of database does not persist data when the Ory Kratos service is stopped or restarted. Therefore, if you want to reset the database, you can simply stop and then restart the Ory Kratos service. All data will be lost when the service is stopped, and a new, empty database will be created when the service is restarted. Here's how you can do it using Docker: 1. Stop the Ory Kratos Docker container:
Copy code
bash docker-compose -f quickstart.yml down
2. Start the Ory Kratos Docker container:
Copy code
bash docker-compose -f quickstart.yml up -d
Please note that this operation will permanently delete all data from your in-memory database. You should ensure that you have saved any data you want to keep before stopping the service. For more information, see the [Ory Kratos Docker](https://www.ory.sh/docs/kratos/guides/docker) and [Data storage and persistence](https://www.ory.sh/docs/self-hosted/deployment#data-storage-and-persistence) documentation.
l
@chilly-king-10285 what command should i put in docker terminal
c
A message from kapa.ai
l
ls
c
If you're using Docker and your DSN is set to
memory
, you can reset the database by simply stopping and restarting the Ory Kratos Docker container. Here's how you can do it: 1. Stop the Ory Kratos Docker container:
Copy code
bash docker-compose down
2. Start the Ory Kratos Docker container:
Copy code
bash docker-compose up -d
Please ensure that you're in the correct directory where your
docker-compose.yml
file is located when running these commands. Remember, when using an in-memory database, all data will be lost when the service is stopped, and a new, empty database will be created when the service is restarted. For more information, see the [Ory Kratos Docker](https://www.ory.sh/docs/kratos/guides/docker) and [Data storage and persistence](https://www.ory.sh/docs/self-hosted/deployment#data-storage-and-persistence) documentation.
l
@chilly-king-10285 how can i add default value in identity schema?
c
A message from kapa.ai
To add a default value in the identity schema, you can use the
default
keyword in your JSON schema. This keyword specifies the default value for the property. Here's an example of how you might do this:
Copy code
json {   "$schema": "<http://json-schema.org/draft-07/schema#>",   "type": "object",   "properties": {     "traits": {       "type": "object",       "properties": {         "jobTitle": {           "type": "string",           "default": "Software Engineer"         }       }     }   } }
In this example, the
jobTitle
property has a default value of
"Software Engineer"
. Please note that the
default
keyword in JSON Schema is just a declarative default and doesn't cause any automatic assignment. You would need to implement the logic in your application to use this default value when no value is provided. For more information, see the [Identity Schema](https://www.ory.sh/docs/kratos/manage-identities/identity-schema) documentation.
l
@chilly-king-10285 how can i use my custom email template for recovery and verification
c
A message from kapa.ai
To use custom email templates for recovery and verification flows in Ory, you need to follow these steps: 1. Create your custom email templates: These can be in HTML or plaintext format. 2. Encode your custom templates to base64: You can use the following command to do this:
Copy code
bash echo "Your custom template" | base64
Or use an online tool like https://www.base64encode.org/. 3. Add your Base64-encoded custom message templates to the config: You need to add
base64://
before the encoded template in your
identity-config.yaml
file:
Copy code
yaml courier:    smtp:    from_name: MyProject via Ory    templates:    recovery:    invalid:    email:    body:    html: "<base64://ENCODED_HTML_TEMPLATE>"    plaintext: "<base64://ENCODED_PLAINTEXT_TEMPLATE>"    valid:    email:    body: {}    verification:    invalid:    email:    body: {}    valid:    email:    body: {}    login:    valid:    email:    body: {}    registration:    valid:    email:    body: {}
4. Upload the edited config: Use the following command to upload the edited config:
Copy code
bash ory update identity-config <project-id> --file updated_config.yaml
In the Ory Network, you can use only Base64-encoded templates.
http://
or
file://
URIs are not supported. If you provide custom templates using unsupported methods, the system uses the default templates. For more information, see the [Using custom message templates](https://www.ory.sh/docs/kratos/emails-sms/custom-email-templates#using-custom-message-templates) documentation.
l
@chilly-king-10285 i am using self hosted
c
A message from kapa.ai
To use custom email templates for recovery and verification flows in a self-hosted Ory Kratos setup, you need to follow these steps: 1. Create your custom email templates: These can be in HTML or plaintext format. 2. Place your custom templates in a directory: This directory will be mounted into the Ory Kratos Docker container. 3. Configure Ory Kratos to use your custom templates: You need to set the
courier.templates.path
configuration option to the path of your custom templates directory inside the Docker container. You can do this in your Ory Kratos configuration file:
Copy code
yaml courier:   templates:     path: /path/to/your/templates
In this example, replace
/path/to/your/templates
with the path of your custom templates directory inside the Docker container. 4. Mount your custom templates directory into the Docker container: You can do this by adding a volume in your
docker-compose.yml
file:
Copy code
yaml services:   kratos:     image: oryd/kratos:v0.7.6-alpha.1     volumes:       - ./path/to/your/templates:/path/to/your/templates
In this example, replace
./path/to/your/templates
with the path of your custom templates directory on your host machine, and
/path/to/your/templates
with the path where you want to mount this directory inside the Docker container. Please note that the specific way you create your custom templates, configure Ory Kratos to use them, and mount them into the Docker container may vary depending on your application's requirements and the specific features of Ory Kratos that you are using. For more information, see the [Emails & SMS](https://www.ory.sh/docs/kratos/emails-sms) documentation.
l
@chilly-king-10285 what is plainText and html in email templates? can you give me a dummy template with configuration in yml?
c
A message from kapa.ai
In Ory Kratos, each email template must have two versions:
html
and
plaintext
. - The
html
version uses HTML syntax to achieve the desired look and functionality (such as clickable buttons) of the email message. - The
plaintext
version can't contain any HTML. It must contain only plain text content and any necessary
gotmpl
logic. This version is used as a fallback when the
html
version cannot be delivered, for example when the user's mail server blocks HTML in all incoming messages. Here's an example of a dummy email template: HTML version (
email.body.gotmpl
):
Copy code
html Hi, please verify your account by clicking the following link:      <a href="{{ .VerificationURL }}">{{ .VerificationURL }}</a>
Plaintext version (
email.body.plaintext.gotmpl
):
Copy code
plaintext Hi, please verify your account by clicking the following link: {{ .VerificationURL }}
And here's how you might configure Ory Kratos to use these custom templates in your
config.yml
file:
Copy code
yaml courier:    template_override_path: /conf/courier-template    templates:    verification:    valid:    email:    body:    html: file:///conf/courier-template/verification/valid/email.body.gotmpl    plaintext: file:///conf/courier-template/verification/valid/email.body.plaintext.gotmpl
In this example, replace
/conf/courier-template/verification/valid/email.body.gotmpl
and
/conf/courier-template/verification/valid/email.body.plaintext.gotmpl
with the actual paths to your custom templates. For more information, see the [Custom Email Templates](https://www.ory.sh/docs/kratos/emails-sms/custom-email-templates) and [Configuration](https://www.ory.sh/docs/kratos/self-hosted/mail-courier-templates#configuration) documentation.
l
@chilly-king-10285, if i am using self hosted in ubuntu without docker, and i created a template directory for email templated, in what format or extension should i add html and plaintext templates?
c
A message from kapa.ai
When using a self-hosted Ory Kratos setup without Docker, you should create your email templates as
.gotmpl
files. This is the file extension for Go templates, which Ory Kratos uses for its email templates. You should create two versions of each email template: an HTML version and a plaintext version. The HTML version should contain your HTML content, and the plaintext version should contain only plain text content. Here's an example of how you might structure your templates directory:
Copy code
/templates   /recovery     /valid       email.body.gotmpl       email.body.plaintext.gotmpl   /verification     /valid       email.body.gotmpl       email.body.plaintext.gotmpl
In this example,
email.body.gotmpl
is the HTML version of the email template, and
email.body.plaintext.gotmpl
is the plaintext version. For more information, see the [Configuration](https://www.ory.sh/docs/kratos/self-hosted/mail-courier-templates#configuration) documentation.
l
@chilly-king-10285 can you give me yml configuration for above cases?
c
A message from kapa.ai
Sorry @lemon-student-13425, I seem to be having a bit of trouble. Don't worry though, I've pinged my support folks and they will try to fix me up! 🧑‍💻 Perhaps try again in 5mins?
l
@chilly-king-10285 i dont want user to create account unless he has verified his accound on verification scree.
c
A message from kapa.ai
Sorry @lemon-student-13425, I seem to be having a bit of trouble. Don't worry though, I've pinged my support folks and they will try to fix me up! 🧑‍💻 Perhaps try again in 5mins?