<@U04UQ68083H> steps to add Passkeys &amp; WebAuth...
# ory-copilot
b
@chilly-king-10285 steps to add Passkeys & WebAuthN in self hosted open source Ory Kratos
b
A message from kapa.ai
# Adding Passkeys & WebAuthN in Self-Hosted Ory Kratos To implement Passkeys and WebAuthN in your self-hosted Ory Kratos instance, follow these steps: ## 1. Choose Your Strategy You can implement passwordless authentication using either: - The dedicated passkey strategy (recommended for better user experience) - The WebAuthN strategy (for backward compatibility) ## 2. Configure Passkeys Strategy For the dedicated passkey strategy, update your Kratos configuration file:
Copy code
yaml selfservice:   methods:     passkey:       enabled: true       config:         rp:           display_name: "Your Application name"           # Set 'id' to the top-level domain           id: localhost           # Set 'origins' to the exact URLs that will prompt users to use WebAuthn           origins:             - <http://localhost:4455>
[Passkeys & WebAuthN documentation](https://www.ory.sh/docs/kratos/passwordless/passkeys#passkeys-with-the-dedicated-passkey-strategy) ## 3. Configure WebAuthN Strategy (Alternative) If you prefer using the WebAuthN strategy:
Copy code
yaml selfservice:   methods:     webauthn:       enabled: true       config:         # Set to true for passwordless flows, false for multi-factor authentication         passwordless: true         rp:           display_name: "Your Application name"           # Set 'id' to the top-level domain           id: localhost           # Set 'origin' to the exact URL of the page that prompts for WebAuthn           origins:             - <http://localhost:4455>
[WebAuthN configuration documentation](https://www.ory.sh/docs/kratos/passwordless/passkeys#configuration-2) ## 4. Update Identity Schema For the passkey strategy, update your identity schema to define which field will be the display name:
Copy code
json {   "$schema": "<http://json-schema.org/draft-07/schema#>",   "type": "object",   "properties": {     "traits": {       "type": "object",       "properties": {         "email": {           "type": "string",           "format": "email",           "title": "Your E-Mail",           "minLength": 3,           "<http://ory.sh/kratos|ory.sh/kratos>": {             "credentials": {               "passkey": {                 "display_name": true               }             }           }         }       }     }   } }
[Identity schema documentation](https://www.ory.sh/docs/kratos/passwordless/passkeys#identity-schema) ## 5. Implement in Your UI For your custom UI to use WebAuthn: 1. Add the WebAuthn JavaScript to your page:
Copy code
html <head>   <script src="/.well-known/ory/webauthn.js"></script> </head>
2. Implement the flow: - Create login flow - Render UI with the
webauthn
or
passkey
group - User enters identifier and clicks "Sign in with security key" - Form submits, starting a new flow - Render UI prompting user to insert security key - User inserts key and continues [Custom UI integration documentation](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration#passwordless-authentication) ## Important Notes - The relying party ID (domain) is crucial for WebAuthn. Changing it after users have registered will break existing logins. - WebAuthn is browser-only and doesn't work with native mobile apps. - WebAuthn is limited to one domain and doesn't work in local environments when using CNAME/Ory Proxy. [Troubleshooting documentation](https://www.ory.sh/docs/troubleshooting/passkeys-webauthn-security-error#relying-party-id-mismatch)
b
@chilly-king-10285 give the complete kratos.yml file to add Passkeys in self hosted open source Ory Kratos
b
A message from kapa.ai
I'll provide a complete
kratos.yml
configuration file for adding Passkeys in a self-hosted Ory Kratos instance.
Copy code
yaml version: v0.11.0  dsn: memory  serve:   public:     base_url: <http://localhost:4433/>     cors:       enabled: true   admin:     base_url: <http://localhost:4434/>  selfservice:   default_browser_return_url: <http://localhost:4455/>   allowed_return_urls:     - <http://localhost:4455>    methods:     passkey:       enabled: true       config:         rp:           display_name: "Your Application name"           # Set 'id' to the top-level domain           id: localhost           # Set 'origins' to the exact URLs that will prompt users to use WebAuthn           origins:             - <http://localhost:4455>     password:       enabled: true     profile:       enabled: true     link:       enabled: false     code:       enabled: false     totp:       enabled: false     lookup_secret:       enabled: false     oidc:       enabled: false    flows:     error:       ui_url: <http://localhost:4455/error>          settings:       ui_url: <http://localhost:4455/settings>       privileged_session_max_age: 15m       required_aal: aal1          recovery:       enabled: true       ui_url: <http://localhost:4455/recovery>       use: code          verification:       enabled: true       ui_url: <http://localhost:4455/verification>       use: code       after:         default_browser_return_url: <http://localhost:4455/>          logout:       after:         default_browser_return_url: <http://localhost:4455/login>          login:       ui_url: <http://localhost:4455/login>       lifespan: 10m          registration:       lifespan: 10m       ui_url: <http://localhost:4455/registration>       after:         password:           hooks:             - hook: session         passkey:           hooks:             - hook: session  log:   level: debug   format: text   leak_sensitive_values: false  secrets:   cookie:     - PLEASE-CHANGE-ME-I-AM-VERY-INSECURE  hashers:   argon2:     parallelism: 1     memory: 128MB     iterations: 2     salt_length: 16     key_length: 16  identity:   default_schema_id: default   schemas:     - id: default       url: file:///etc/config/kratos/identity.schema.json  courier:   smtp:     connection_uri: <smtps://test:test@mailslurper:1025/?skip_ssl_verify=true>
This configuration enables the Passkey strategy for passwordless authentication. You'll also need to create an identity schema file (
identity.schema.json
) that defines which field will be used as the display name for passkeys:
Copy code
json {   "$schema": "<http://json-schema.org/draft-07/schema#>",   "type": "object",   "properties": {     "traits": {       "type": "object",       "properties": {         "email": {           "type": "string",           "format": "email",           "title": "Your E-Mail",           "<http://ory.sh/kratos|ory.sh/kratos>": {             "credentials": {               "passkey": {                 "display_name": true               }             },             "verification": {               "via": "email"             },             "recovery": {               "via": "email"             }           }         },         "name": {           "type": "object",           "properties": {             "first": {               "type": "string"             },             "last": {               "type": "string"             }           }         }       },       "required": ["email"],       "additionalProperties": false     }   } }
Important notes: 1. Replace
localhost
with your actual domain in production 2. Update the SMTP settings for your email provider 3. Change the cookie secrets to secure values 4. Adjust the allowed return URLs to match your frontend application 5. The identity schema must define which field is used as the display name for passkeys [Passkeys & WebAuthN documentation](https://www.ory.sh/docs/kratos/passwordless/passkeys#passkeys-with-the-dedicated-passkey-strategy) provides more details on configuring passkeys in Ory Kratos.
b
on clicking the button nothing is happening
@chilly-king-10285 on clicking the button nothing is happening
b
A message from kapa.ai
I'll help you troubleshoot why nothing happens when clicking the button in your Ory Kratos implementation with Passkeys. Based on the knowledge sources, there are several common issues that could cause this problem: ### Possible Causes and Solutions 1. WebAuthn JavaScript Integration Issue The button click for WebAuthn/Passkeys requires proper JavaScript execution. Make sure you've included the WebAuthn script in your page:
Copy code
html    <script src="/.well-known/ory/webauthn.js" async referrerpolicy="no-referrer" crossorigin="anonymous"></script>
The UI node for WebAuthn buttons contains an
onclick
attribute with JavaScript that needs to be properly executed. In single-page applications, this requires special handling as noted in the [Button input node documentation](https://www.ory.sh/docs/kratos/concepts/ui-user-interface#button-input-node). 2. Browser Compatibility Issues WebAuthn is a browser standard and has some constraints: - It doesn't work in native mobile apps - It's limited to one domain - It doesn't work in local environments when using CNAME/Ory Proxy [WebAuthn constraints documentation](https://www.ory.sh/docs/kratos/passwordless/passkeys#constraints) 3. Relying Party ID Mismatch This is a common issue that can prevent WebAuthn from working: > The relying party ID is not a registrable domain suffix of, nor equal to the current domain. If you're using Ory Tunnel, Ory Proxy, or other tooling that proxies requests to a different domain, you may need to update your configuration:
Copy code
ory patch identity-config --project <project-id> --workspace <workspace-id> \      --replace "/selfservice/methods/passkey/config/rp/id=\"localhost\"" \      --replace "/selfservice/methods/passkey/config/rp/origins=[\"<http://localhost:3000\>"]" \      --format yaml
[Troubleshooting documentation](https://www.ory.sh/docs/troubleshooting/passkeys-webauthn-security-error#relying-party-id-mismatch) 4. CSRF Issues If you're running over HTTP without
--dev
mode, cookies might have the
Secure
flag enabled by default, preventing them from being sent. Try running with the
--dev
flag for local development:
Copy code
kratos serve --dev
Also ensure you're not mixing up domains like
127.0.0.1
and
localhost
which are treated as separate domains for cookies. [CSRF troubleshooting documentation](https://www.ory.sh/docs/kratos/debug/csrf) 5. Browser Console Errors Check your browser's developer console for any JavaScript errors that might provide more specific information about what's failing. If you can provide more specific details about your implementation and any error messages you're seeing in the browser console, I can offer more targeted troubleshooting advice. Would you like me to elaborate on any of these potential solutions?
b
@chilly-king-10285 how to show passkey option in signup also ?
b
A message from kapa.ai
To show the passkey option during signup in Ory Kratos, you need to ensure that the passkey method is properly configured and enabled for registration flows. Here's how to do it: ## Enable Passkey for Registration 1. Update your Kratos configuration Make sure your
kratos.yml
has the passkey method enabled:
Copy code
yaml    selfservice:      methods:        passkey:          enabled: true          config:            rp:              display_name: "Your Application name"              id: localhost              origins:                - <http://localhost:4455>      flows:        registration:          after:            passkey:              hooks:                - hook: session
The important part is ensuring that passkey is enabled and that you have the registration hooks configured for the passkey method. 2. Update your identity schema Make sure your identity schema has a field designated as the display name for passkeys:
Copy code
json    {      "traits": {        "properties": {          "email": {            "type": "string",            "format": "email",            "title": "Email",            "<http://ory.sh/kratos|ory.sh/kratos>": {              "credentials": {                "passkey": {                  "display_name": true                }              }            }          }        }      }    }
This tells Kratos which field to use as the display name for passkeys [Identity schema documentation](https://www.ory.sh/docs/kratos/passwordless/passkeys#identity-schema). 3. Include WebAuthn JavaScript in your UI Make sure your registration page includes the WebAuthn JavaScript:
Copy code
html    <head>      <script src="/.well-known/ory/webauthn.js"></script>    </head>
This script is required for the passkey functionality to work properly [Custom UI integration documentation](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration#passwordless-authentication). 4. Render the passkey option in your UI When rendering your registration form, make sure to include the UI nodes from the
passkey
group. The registration flow JSON response will include all the necessary information to render the passkey option. If you're using a custom UI, you'll need to ensure that you're properly rendering all UI nodes, including those in the passkey group. If the passkey option still isn't showing up in your registration form, check your browser's console for any JavaScript errors and verify that the registration flow response includes nodes for the passkey method. Remember that WebAuthn has some constraints, such as only working in secure contexts (HTTPS or localhost) and requiring proper domain configuration. Make sure your development environment meets these requirements. Would you like more specific guidance on any of these steps?
b
@chilly-king-10285 /.well-known/ory/webauthn.js is throwing 404
b
A message from kapa.ai
I see you're encountering a 404 error when trying to load the WebAuthn JavaScript file. This is a common issue when implementing passkeys in Ory Kratos. Let me help you troubleshoot this problem. ### Why You're Getting a 404 Error The
/.well-known/ory/webauthn.js
file is served by Ory Kratos and is essential for WebAuthn/Passkey functionality. A 404 error indicates that your application can't find this file. Here are some possible reasons and solutions: 1. Incorrect URL Path Make sure you're using the correct path to the WebAuthn JavaScript file. The path should be relative to your Kratos public API:
Copy code
html    <script src="https://your-kratos-public-url/.well-known/ory/webauthn.js"></script>
If you're using Ory Network or a custom domain, the URL might need to include additional path segments:
Copy code
html    <script src="https://your-custom-domain/api/kratos/public/.well-known/ory/webauthn.js"></script>
2. CORS Issues If you're loading the script from a different domain than your application, you might encounter CORS issues. This was a known issue in Ory Network as reported in [this GitHub issue](https://github.com/ory/network/issues/64). Make sure your Kratos configuration has CORS enabled:
Copy code
yaml    serve:      public:        cors:          enabled: true
3. Proxy Configuration If you're using a proxy (like Ory Tunnel or Nginx), ensure it's correctly forwarding requests to the Kratos public API. 4. API Endpoint Configuration Check that your Kratos public API is properly configured and accessible. The WebAuthn JavaScript is served from the frontend API group as documented in the [Ory API Reference](https://www.ory.sh/docs/reference/api). ### Solutions to Try 1. Verify the correct URL Check the browser's network tab to see the exact URL that's returning 404. Make sure it matches your Kratos public API URL. 2. Use the full URL path Instead of a relative path, try using the full URL to the WebAuthn JavaScript file:
Copy code
html    <script src="http://localhost:4433/.well-known/ory/webauthn.js"></script>
Replace
localhost:4433
with your actual Kratos public API URL. 3. Check Kratos logs Look at your Kratos server logs for any errors related to serving the WebAuthn JavaScript file. 4. Verify Kratos is running Make sure your Kratos server is running and accessible at the URL you're using. If you continue to have issues, please provide more details about your setup, such as whether you're using self-hosted Kratos or Ory Network, and any proxy or custom domain configuration you might have.
b
@chilly-king-10285 how do i update this endpoint full url path in Ory Kratos ReactJS / NextJS User Interface Reference Implementation
b
A message from kapa.ai
I'll help you update the WebAuthn JavaScript endpoint URL path in the Ory Kratos ReactJS/NextJS UI reference implementation. In the reference implementations, you need to modify how the WebAuthn script is loaded. The issue you're facing with the 404 error is likely because the UI is trying to load the script from the wrong path. For the React/NextJS reference implementation, you'll need to update the component that renders the WebAuthn button. Here's how to do it: 1. Locate the component that renders the WebAuthn script In the reference implementation, there's typically a component that handles rendering UI nodes, including the WebAuthn script node. Look for a component that processes the
script
node type. 2. Update the script source URL When you find the component that renders the script tag, update the
src
attribute to use the full URL path to your Kratos instance:
Copy code
jsx    // Example of how to update the script source in a React component    const NodeScript = ({ attributes }) => {      // Replace this URL with your actual Kratos public URL      const fullWebAuthnUrl = "<https://your-kratos-public-url/.well-known/ory/webauthn.js>";            return (        <script          id={attributes.id}          src={fullWebAuthnUrl}          async={attributes.async}          referrerPolicy={attributes.referrerpolicy}          crossOrigin={attributes.crossorigin}          integrity={attributes.integrity}          type={attributes.type}        />      );    };
3. For button components with onclick handlers If you're also having issues with the WebAuthn button not working, you might need to update how the
onclick
attribute is handled:
Copy code
jsx    const NodeInputButton = ({ node }) => {      const { attributes } = node;            // Create a safe onClick handler that executes the WebAuthn script      const handleClick = React.useCallback(() => {        // This safely executes the onclick JavaScript from the node        if (attributes.onclick) {          // eslint-disable-next-line no-eval          eval(attributes.onclick);        }      }, [attributes.onclick]);            return (        <button          name={attributes.name}          onClick={handleClick}          value={attributes.value || ""}          disabled={attributes.disabled}        >          {node.meta?.label?.text}        </button>      );    };
The [Button input node documentation](https://www.ory.sh/docs/kratos/concepts/ui-user-interface#button-input-node) mentions that in SPAs, you need special handling for the
onclick
attribute, which often requires using
eval
to execute the WebAuthn JavaScript. If you're using the official Ory reference implementation, you might want to check the [Ory Kratos React NextJS UI repository](https://github.com/ory/kratos-react-nextjs-ui) for the most up-to-date implementation details. Remember that WebAuthn has domain constraints, so make sure your Kratos configuration has the correct domain settings for the relying party ID and origins. Would you like more specific guidance for a particular reference implementation?
b
@chilly-king-10285 SecurityError: The relying party ID is not a registrable domain suffix of, nor equal to the current domain. Subsequently, an attempt to fetch the .well-known/webauthn resource of the claimed RP ID failed.
b
A message from kapa.ai
I see you're encountering a common SecurityError with WebAuthn/Passkeys in Ory Kratos. This specific error occurs when there's a mismatch between your configured Relying Party ID and the domain you're actually using. ## Why This Error Occurs This error happens because WebAuthn has strict security requirements about domains. The Relying Party ID (RP ID) must be either: - Equal to the current domain where your application is running - A registrable domain suffix of the current domain (like a parent domain) ## How to Fix It Based on the [Ory troubleshooting documentation](https://www.ory.sh/docs/troubleshooting/passkeys-webauthn-security-error#relying-party-id-mismatch), here's how to resolve this issue: 1. Update your WebAuthn/Passkey configuration to match the domain you're actually using:
Copy code
# For Passkeys    ory patch identity-config --project <project-id> --workspace <workspace-id> \      --replace "/selfservice/methods/passkey/config/rp/id=\"localhost\"" \      --replace "/selfservice/methods/passkey/config/rp/origins=[\"<http://localhost:3000\>"]" \      --format yaml        # For WebAuthn    ory patch identity-config --project <project-id> --workspace <workspace-id> \      --replace "/selfservice/methods/webauthn/config/rp/id=\"localhost\"" \      --replace "/selfservice/methods/webauthn/config/rp/origins=[\"<http://localhost:3000\>"]" \      --format yaml
2. If you're using self-hosted Kratos, update your configuration file directly:
Copy code
yaml    selfservice:      methods:        passkey:          config:            rp:              id: "localhost"  # Use your actual domain here              origins:                - "<http://localhost:3000>"  # Use your actual origin URL
## Important Notes 1. Domain constraints: WebAuthn credentials are bound to a specific domain and cannot be shared across domains. As noted in the [Ory blog](https://www.ory.sh/blog/overview-login-password-passkey-webauthn-totp-sso-faceid), "WebAuthn is not multi-domain capable." 2. Production warning: Be careful when changing the RP ID in production environments. As the documentation warns: "Do not change the RP ID in production environments" as this will break existing user credentials. 3. Local development: If you're using Ory Tunnel or Proxy for local development, you may need special configuration as mentioned in the [custom domains documentation](https://www.ory.sh/docs/guides/custom-domains). 4. Consistency: Make sure you're using the same domain throughout your application. Mixing domains like
127.0.0.1
and
localhost
can cause issues as they're treated as different domains. Let me know if you need more specific guidance based on your setup!
b
@chilly-king-10285 what is rp.id if my app is hosted on https://logana.onrender.com/login
b
A message from kapa.ai
Based on your domain
<https://logana.onrender.com/login>
, the correct Relying Party ID (rp.id) for your WebAuthn/Passkey configuration should be:
Copy code
<http://logana.onrender.com|logana.onrender.com>
The RP ID must be a registrable domain suffix of the domain where your application is running. For WebAuthn/Passkeys, you should use the top-level domain without the protocol (https://), port, or path components. Your configuration should look like this:
Copy code
yaml selfservice:   methods:     passkey:       config:         rp:           id: "<http://logana.onrender.com|logana.onrender.com>"           origins:             - "<https://logana.onrender.com>"
The
origins
value must include the full URL with protocol (https://), but without the path component (/login). This configuration follows the WebAuthn security requirements as documented in the [Ory troubleshooting guide](https://www.ory.sh/docs/troubleshooting/passkeys-webauthn-security-error#relying-party-id-mismatch), which specifies that the RP ID must match the domain where your application is running. Remember that changing the RP ID after users have registered will break existing credentials, so be careful when updating this value in production environments.
b
@chilly-king-10285 after succesful login it is redirecting https://logana.onrender.com/self-service/login?flow=61d349eb-3e9c-415b-b0bf-0cf7d0b3e4fa
b
A message from kapa.ai
I see you're having an issue with redirects after successful login in your Ory Kratos implementation. This is a common issue where the redirect URL isn't working as expected. Based on the knowledge sources, this appears to be related to the
return_to
parameter not being properly handled. Let me explain how to fix this: ## Why This Is Happening After successful authentication, Ory Kratos should redirect to your configured default return URL, but instead it's redirecting back to the login flow. This can happen for several reasons: 1. The
return_to
parameter isn't being properly set or persisted 2. The default browser return URL isn't configured correctly 3. There might be an issue with how redirects are handled in your implementation ## How to Fix It Here are the steps to fix the redirect issue: ### 1. Configure Default Redirect URLs Update your Kratos configuration to set the proper redirect URLs:
Copy code
yaml selfservice:   flows:     login:       after:         default_browser_return_url: <https://logana.onrender.com/dashboard>         password:           default_browser_return_url: <https://logana.onrender.com/dashboard>         passkey:           default_browser_return_url: <https://logana.onrender.com/dashboard>
This tells Kratos where to redirect users after successful login [Redirect flows documentation](https://www.ory.sh/docs/concepts/redirects#redirect-flows). ### 2. Use
return_to
Parameter When initializing the login flow, include a
return_to
parameter:
Copy code
<https://logana.onrender.com/self-service/login/browser?return_to=https://logana.onrender.com/dashboard>
This parameter specifies where to redirect after successful authentication [Advanced redirects documentation](https://www.ory.sh/docs/kratos/bring-your-own-ui/custom-ui-advanced-integration#advanced-redirects). ### 3. For API/SPA Flows If you're using an API flow with a single-page application, the redirect won't happen automatically. As mentioned in [this GitHub issue](https://github.com/ory/network/issues/51), you need to handle the redirect in your application code:
Copy code
javascript .then((res) => {   router.push('/dashboard') })
### 4. Check for Redirect Loops If you're experiencing redirect loops, it might be related to an issue described in [this GitHub issue](https://github.com/ory/network/issues/119) where the
return_to
parameter isn't being properly passed between flows. ## Additional Troubleshooting If you're still having issues, check: 1. That your allowed return URLs include your target URL:
Copy code
yaml    selfservice:      allowed_return_urls:        - <https://logana.onrender.com/dashboard>
2. That you're not mixing browser and API flows, which can cause redirect issues 3. That your UI is correctly handling the flow data and not overriding the return URL Let me know if you need more specific guidance based on your implementation!