### Clone Hanko Repository Source: https://github.com/teamhanko/hanko/blob/main/quickstart/README.md Clone the Hanko repository to your local machine to access the quickstart example. ```bash git clone https://github.com/teamhanko/hanko.git ``` -------------------------------- ### Install Hanko Frontend SDK Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Install the Hanko frontend SDK using npm, yarn, or pnpm. ```shell # npm npm install @teamhanko/hanko-frontend-sdk # yarn yarn add @teamhanko/hanko-frontend-sdk # pnpm pnpm install @teamhanko/hanko-frontend-sdk ``` -------------------------------- ### Run Hanko Quickstart with Docker Compose Source: https://github.com/teamhanko/hanko/blob/main/quickstart/README.md Build and run the Hanko quickstart services using Docker Compose. Ensure Docker Desktop is running. ```bash docker compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart" up --build ``` -------------------------------- ### PostgreSQL Database URL Example Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-database-properties-url Example of a PostgreSQL connection URL for Hanko configuration. Ensure the database driver is available. ```yaml postgres://hanko:hanko@localhost:5432/hanko ``` -------------------------------- ### Install Hanko Binary with eget Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Install Hanko binaries from GitHub releases using the eget tool. ```bash eget teamhanko/hanko ``` -------------------------------- ### Start Public and Admin APIs Together Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Start both the public and administrative APIs of Hanko using a single command. ```shell serve all ``` -------------------------------- ### Run React Example with Docker Compose Source: https://github.com/teamhanko/hanko/blob/main/frontend/examples/README.md Use this command to run the React frontend example along with the Hanko API using Docker Compose. Ensure you have the necessary Docker Compose files. ```bash docker compose -f deploy/docker-compose/base.yaml -f deploy/docker-compose/todo-react.yaml -p "hanko-todo-react" up --build ``` -------------------------------- ### Run Vue Example with Docker Compose Source: https://github.com/teamhanko/hanko/blob/main/frontend/examples/README.md Use this command to run the Vue frontend example along with the Hanko API using Docker Compose. Ensure you have the necessary Docker Compose files. ```bash docker compose -f deploy/docker-compose/base.yaml -f deploy/docker-compose/todo-vue.yaml -p "hanko-todo-vue" up --build ``` -------------------------------- ### Run Svelte Example with Docker Compose Source: https://github.com/teamhanko/hanko/blob/main/frontend/examples/README.md Use this command to run the Svelte frontend example along with the Hanko API using Docker Compose. Ensure you have the necessary Docker Compose files. ```bash docker compose -f deploy/docker-compose/base.yaml -f deploy/docker-compose/todo-svelte.yaml -p "hanko-todo-svelte" up --build ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/teamhanko/hanko/blob/main/e2e/README.md Install Node.js dependencies and Playwright browsers after the services are running. Execute these commands from the 'e2e' directory. ```shell npm install npx playwright install chromium ``` -------------------------------- ### Start Admin API Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Start only the Hanko administrative API. The default port is 8001. ```shell serve admin ``` -------------------------------- ### Run Angular Example with Docker Compose Source: https://github.com/teamhanko/hanko/blob/main/frontend/examples/README.md Use this command to run the Angular frontend example along with the Hanko API using Docker Compose. Ensure you have the necessary Docker Compose files. ```bash docker compose -f deploy/docker-compose/base.yaml -f deploy/docker-compose/todo-angular.yaml -p "hanko-todo-angular" up --build ``` -------------------------------- ### Hanko Database URL Example Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-database An example of a datasource connection string for PostgreSQL, which can be used instead of individual database configuration options. If provided, this URL takes precedence. ```yaml postgres://hanko:hanko@localhost:5432/hanko ``` -------------------------------- ### Start Public API from Binary Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Run the Hanko public API using a pre-built binary. Specify the configuration file path using the --config flag. ```shell ./hanko serve public --config ``` -------------------------------- ### Run Next.js Example with Docker Compose Source: https://github.com/teamhanko/hanko/blob/main/frontend/examples/README.md Use this command to run the Next.js frontend example along with the Hanko API using Docker Compose. Ensure you have the necessary Docker Compose files. ```bash docker compose -f deploy/docker-compose/base.yaml -f deploy/docker-compose/todo-nextjs.yaml -p "hanko-todo-nextjs" up --build ``` -------------------------------- ### Start Services with Docker Compose (Passwords Enabled via Config) Source: https://github.com/teamhanko/hanko/blob/main/e2e/README.md After configuring 'deploy/docker-compose/config.yaml' for password enabled, use this command to start the services. It supports both Docker Compose v1 and v2. ```shell # compose v1 docker-compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart-pw" up --build # compose v2 docker compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart-pw" up --build ``` -------------------------------- ### Build Hanko Backend from Source Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Builds the Hanko backend executable from source code. Requires Go (v1.18+) to be installed. ```shell go generate ./... go build -a -o hanko main.go ``` -------------------------------- ### Start Public API with Docker Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Run the Hanko public API using Docker, mounting a configuration file and exposing port 8000. ```shell docker run --mount type=bind,source=,target=/config/config.yaml -p 8000:8000 -it ghcr.io/teamhanko/hanko:latest serve public ``` -------------------------------- ### Install Hanko Elements via npm, yarn, or pnpm Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Install the Hanko Elements module using your preferred package manager. This is the first step to integrating Hanko into your project. ```shell # npm npm install @teamhanko/hanko-elements # yarn yarn add @teamhanko/hanko-elements # pnpm pnpm install @teamhanko/hanko-elements ``` -------------------------------- ### Example Third-Party Redirect URL Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-third_party-properties-redirect_url This is an example of a valid redirect URL for third-party integrations. Ensure this URL is correctly configured in your third-party application settings. ```yaml https://yourinstance.com/thirdparty/callback ``` -------------------------------- ### Configure Webhooks using Environment Variable Source: https://github.com/teamhanko/hanko/wiki/Using-environment-variables Configure Webhooks with complex structures. This example shows how to set multiple webhook hooks with their callbacks and events. ```shell export WEBHOOKS_HOOKS='{"callback":"http://app.com/usercb","events":["user"]};{"callback":"http://app.com/emailcb","events":["email.send"]}' ``` -------------------------------- ### Session JWT Template Example Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Example of configuring custom claims for session JWTs using Go's text/template syntax. Access user data via the .User field. ```yaml session: jwt_template: claims: user_id: "{{ .User.UserID }}" email: "{{ .User.Email.Address }}" ``` -------------------------------- ### Run MySQL Docker Container Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Starts a MySQL database instance using Docker. Ensure to replace placeholders with your desired credentials and port. ```shell docker run --name=mysql \ -e MYSQL_USER= \ -e MYSQL_PASSWORD= \ -e MYSQL_DATABASE= \ -e MYSQL_RANDOM_ROOT_PASSWORD=true \ -p :3306 \ -d mysql:latest ``` -------------------------------- ### Example YAML Configuration with Templated Values Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Illustrates a sample YAML configuration file showcasing static values, templated user data (email, verification status), nested maps, and conditional logic within templates. ```yaml role: "user" # Static value user_email: "{{.User.Email.Address}}" # Templated string is_verified: "{{.User.Email.IsVerified}}" # Boolean from user data metadata: # Nested map greeting: "Hello {{.User.Username}}" source: '{{ .User.Metadata.Public "display_name" }}' # Data read from public metadata ui_theme: '{{ .User.Metadata.Unsafe "ui_theme" }}' # Data read from unsafe metadata scopes: # Slice with templated value - "read" - "write" - "{{if .User.Email.IsVerified}}admin{{else}}basic{{end}}" ``` -------------------------------- ### Start Services with Docker Compose (Passwords Enabled) Source: https://github.com/teamhanko/hanko/blob/main/e2e/README.md Use this command to set up and run the necessary services for testing when password authentication is enabled. It supports both Docker Compose v1 and v2. ```shell # compose v1 PASSWORD_ENABLED=true docker-compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart-pw" up --build # compose v2 PASSWORD_ENABLED=true docker compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart-pw" up --build ``` -------------------------------- ### Run PostgreSQL Docker Container Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Starts a PostgreSQL database instance using Docker. Ensure to replace placeholders with your desired credentials and port. ```shell docker run --name=postgres \ -e POSTGRES_USER= \ -e POSTGRES_PASSWORD= \ -e POSTGRES_DB= \ -p :5432 \ -d postgres ``` -------------------------------- ### Security Keys Limit Configuration Example Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-mfa-properties-security_keys-properties-limit This snippet shows how to set the maximum number of security keys a user can register. The value must be an integer. ```json 10 ``` -------------------------------- ### Hanko Events Web Component Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Example of using the hanko-events web component to listen for session creation events. ```html ``` -------------------------------- ### Start Services with Docker Compose (Passwords Disabled) Source: https://github.com/teamhanko/hanko/blob/main/e2e/README.md Use this command to set up and run the necessary services for testing when password authentication is disabled. It supports both Docker Compose v1 and v2. ```shell # compose v1 docker-compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart-nopw" up --build # compose v2 docker compose -f deploy/docker-compose/quickstart.yaml -p "hanko-quickstart-nopw" up --build ``` -------------------------------- ### Webhook Hooks Configuration Example Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-webhooks Defines a list of webhook configurations, each with a callback URL and a list of events to subscribe to. This format is used when specifying the WEBHOOKS_HOOKS environment variable. ```json {"callback":"http://app.com/usercb","events":["user"]};{"callback":"http://app.com/emailcb","events":["email.send"]} ``` -------------------------------- ### Initialize a New Flow with Hanko FlowAPI Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Start a new authentication or profile flow using the createState method. Options can control event dispatching and auto-step behavior. ```typescript const state = await hanko.createState("login", { dispatchAfterStateChangeEvent: true, excludeAutoSteps: [], loadFromCache: true, cacheKey: "hanko-flow-state", }); ``` -------------------------------- ### Provide Custom CSS Rules for Light DOM Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md When `injectStyles` is set to `false`, you must provide all CSS rules yourself. This example demonstrates how to set the background color and includes a placeholder for more rules. ```css .hanko_container { background-color: blue; } /* more css rules... */ ``` -------------------------------- ### Style Hanko Form Items using Shadow Parts Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Example of styling form items within the hanko-auth component to stack vertically using the ::part selector. ```html ``` -------------------------------- ### Rate Limiter Store Options Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-rate_limiter The 'store' property specifies where rate limiting state is kept. It's an optional string that can be either 'in_memory' or 'redis'. Using 'redis' is recommended for multi-instance setups. ```json "in_memory" ``` ```json "redis" ``` -------------------------------- ### Get WebAuthn Assertion Source: https://github.com/teamhanko/hanko/blob/main/backend/flow_api/static/generic_client.html Parses request options from a JSON payload and uses the WebAuthn API to get an assertion. Returns the response as a JSON string. ```javascript async function webauthnGet(payload) { const options = parseRequestOptionsFromJSON(payload) const response = await get(options) return JSON.stringify(response) } ``` -------------------------------- ### Initialize Hanko SDK (CDN) Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Include the Hanko SDK via a CDN script tag and initialize it in your HTML. ```html ``` -------------------------------- ### Initialize UI and Event Listeners Source: https://github.com/teamhanko/hanko/blob/main/backend/flow_api/static/generic_client.html Initializes the application by setting up an event listener for a button that triggers the creation of a new login flow. ```javascript function init() { const newLoginFlowBtnEL = document.getElementById("newLoginFlowBtn"); newLoginFlowBtnEL.addEventListener("click", () => { createFlow(); }); } init(); ``` -------------------------------- ### Apply Database Migrations from Source Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Applies database migrations for the Hanko backend using the locally built executable. The config file path can be relative or absolute. ```shell ./hanko migrate up --config ``` -------------------------------- ### acquire_on_login Options Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-passkey Defines when users are prompted to create a passkey on login. Options include 'always', 'conditional', and 'never'. ```json "always" ``` ```json "conditional" ``` ```json "never" ``` -------------------------------- ### WebAuthn Relying Party Configuration (example.com) Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Configure the WebAuthn relying party ID and origins when the login is hosted at the same domain as the main application. ```yaml webauthn: relying_party: id: "example.com" display_name: "Example Project" origins: - "https://example.com" ``` -------------------------------- ### Run Backend Unit Tests Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Execute all unit tests for the Hanko backend. Run this command from within the 'backend' directory. ```bash go test -v ./... ``` -------------------------------- ### Get Selected Flow Path Source: https://github.com/teamhanko/hanko/blob/main/backend/flow_api/static/generic_client.html Retrieves the selected flow path from a dropdown element with the ID 'options'. This is used to determine which API endpoint to call. ```javascript function getFlowPath() { const optionsEl = document.getElementById("options"); const selectedIndex = optionsEl.selectedIndex; return "/" + optionsEl.options[selectedIndex].value; } ``` -------------------------------- ### Apply Database Migrations with Docker Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Applies database migrations for the Hanko backend using a Docker container. The path to the configuration file must be absolute. ```shell docker run --mount type=bind,source=,target=/config/config.yaml -p 8000:8000 -it ghcr.io/teamhanko/hanko:latest migrate up ``` -------------------------------- ### Run Mailslurper Docker Container Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Starts a Mailslurper container for local SMTP testing. Ports 2500 (SMTP), 8080 (GUI), and 8085 (API) are exposed. ```shell docker run --name=mailslurper -it -p 2500:2500 -p 8080:8080 -p 8085:8085 @marcopas/docker-mailslurper ``` -------------------------------- ### Build and Deploy with Skaffold Source: https://github.com/teamhanko/hanko/blob/main/deploy/k8s/overlays/thirdparty-x-domain/README.md Use Skaffold to build and deploy the application to your local Kubernetes cluster using the 'thirdparty-x-domain' profile. ```bash skaffold run -p thirdparty-x-domain ``` -------------------------------- ### Hanko SDK Initialization Options Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Initialize the Hanko SDK with custom options for timeout, cookie name, local storage key, session check interval, and broadcast channel name. ```javascript const defaultOptions = { timeout: 13000, // The timeout (in ms) for the HTTP requests. cookieName: "hanko", // The cookie name under which the session token is set. localStorageKey: "hanko", // The prefix / name of the localStorage keys. sessionCheckInterval: 30000, // Interval (in ms) for session validity checks. Must be greater than 3000 (3s). sessionCheckChannelName: "hanko-session-check" // The broadcast channel name for inter-tab communication }; const hanko = new Hanko("http://localhost:3000", defaultOptions); ``` -------------------------------- ### WebAuthn Relying Party Configuration (example.com with subdomain origin) Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Configure the WebAuthn relying party ID to 'example.com' while allowing origins from a subdomain, useful for future flexibility. ```yaml webauthn: relying_party: id: "example.com" display_name: "Example Project" origins: - "https://login.example.com" ``` -------------------------------- ### Attribute Mapping Example Source: https://github.com/teamhanko/hanko/wiki/reference/config/config-properties-third_party-properties-custom_providers-custom_provider Maps standard OIDC claims to claims from a third-party provider. Useful when the provider's userinfo endpoint does not return OIDC conformant claims. ```yaml attribute_mapping: sub: user_id ``` -------------------------------- ### Register Hanko Web Components Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Call the register() function with the Hanko API URL to register the web components. This is the basic setup required before using any Hanko elements. ```javascript const { hanko } = await register("https://hanko.yourdomain.com"); ``` -------------------------------- ### Override Default CSS with Light DOM Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md When using light DOM support (shadow: false), you can provide your own CSS rules. This example shows how to override the background color of the container. ```css .hanko_container { background-color: blue !important; } ``` -------------------------------- ### Create OIDC Client Environment File Source: https://github.com/teamhanko/hanko/blob/main/deploy/k8s/overlays/thirdparty-x-domain/README.md Create a .env file with your OIDC client ID and secret. This is required before running the deployment. ```bash client_id=your-id client_secret=your-secret ``` -------------------------------- ### Embed Hanko Auth Component Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Embed the hanko-auth web component in your HTML and attach an event listener for session creation. This example demonstrates basic integration and event handling. ```html ``` -------------------------------- ### WebAuthn Relying Party Configuration (login.example.com) Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Configure the WebAuthn relying party ID and origins when the login is hosted at a subdomain. ```yaml webauthn: relying_party: id: "login.example.com" display_name: "Example Project" origins: - "https://login.example.com" ``` -------------------------------- ### Initialize Hanko SDK (Module) Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Import and initialize the Hanko SDK as a module in your TypeScript or JavaScript project. ```typescript import { Hanko } from "@teamhanko/hanko-frontend-sdk" const hanko = new Hanko("http://localhost:3000") ``` -------------------------------- ### Advanced State Serialization and Deserialization Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Provides methods for custom persistence of authentication flow state. Use `serialize` to get a storable object and `deserialize` to recover state with a custom cache key. ```typescript import { State } from "@teamhanko/hanko-frontend-sdk"; const serialized = state.serialize(); // Returns a `SerializedState` object // Store `serialized` in your storage system // Later, deserialize it const recoveredState = await State.deserialize(hanko, serialized, { cacheKey: "custom-key", }); ``` -------------------------------- ### Get Session Token Source: https://github.com/teamhanko/hanko/blob/main/frontend/frontend-sdk/README.md Retrieves the current session's JWT token. This method is non-throwing and returns null if no active session exists. Useful for scenarios requiring manual token handling. ```typescript const token = hanko.getSessionToken(); console.log("Session token:", token); // Example output: "eyJhbGciOiJIUzI1NiIs..." ``` -------------------------------- ### Handle Session Creation Event with Hanko SDK Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Sets up a listener for the session creation event to log JWT claims. ```javascript // Handle session creation event hanko.onSessionCreated(({ claims }) => { console.log("Session created with JWT claims:", claims); }); ``` -------------------------------- ### Get WebAuthn Assertion for Conditional UI Source: https://github.com/teamhanko/hanko/blob/main/backend/flow_api/static/generic_client.html Parses request options and sets mediation to 'conditional' for the WebAuthn API. Aborts any previous request and returns the assertion as a JSON string. Handles AbortError specifically. ```javascript async function webauthnGetConditional(payload) { const options = parseRequestOptionsFromJSON(payload) options.mediation = "conditional"; if (abortController) { abortController.abort() } abortController = new AbortController(); options.signal = abortController.signal let assertion; try { assertion = await get(options); } catch (e) { if (e.name === 'AbortError') { console.warn('Conditional UI: aborting credential get request'); return; } throw new Error(e); } return JSON.stringify(assertion) } ``` -------------------------------- ### Enable Webhooks Configuration Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md YAML snippet to enable webhooks and specify a callback URL and events to listen for. ```yaml webhooks: enabled: true hooks: - callback: events: - user ``` -------------------------------- ### User Import with Username and Hashed Password Source: https://github.com/teamhanko/hanko/wiki/reference/import/user_import This snippet demonstrates importing a user using a username and a pre-hashed password. It includes the password hash, creation, and update timestamps. Note that `user_id`, `otp_secret`, and `emails` are not provided in this format. ```yaml - emails: null username: example password: password: $2a$12$mFbud0mLsD/q.WG7/9pNQemlAHs3H4o8zAv44gsUF1v1awsdqTh7. created_at: '2024-08-17T12:05:15.651387237Z' updated_at: '2024-08-17T12:05:15.651387237Z' otp_secret: null ``` -------------------------------- ### Basic SMTP Configuration for Hanko Backend Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Minimal configuration for email delivery using a local SMTP server like Mailslurper. Ensure 'email_delivery.enabled' is true. ```yaml email_delivery: enabled: true email: from_address: no-reply@example.com from_name: Example Application smtp: host: localhost port: 2500 ``` -------------------------------- ### Enable Shadow DOM for Hanko Components Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Demonstrates how to enable the shadow DOM for Hanko web components by passing the 'shadow: true' option during registration. ```javascript register("https://hanko.yourdomain.com", { shadow: true }); // equals register("https://hanko.yourdomain.com"); ``` -------------------------------- ### Hanko Web Component Initialization and Event Handling Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/src/example.html Initializes Hanko Web Components, sets up event listeners for session events, and manages the visibility of authentication and profile components. This snippet requires the Hanko Elements library to be imported. ```javascript // Uncomment the following two lines if you want to import the local build, which can be created by changing to // the "/frontend" directory and running "npm run build:elements". // import {register} from "../dist/elements.js"; // import {all} from "../dist/i18n/all.js"; // Comment the following two lines if you don't want to import Hanko Elements from the CDN, see comment above. // import {register} from "https://cdn.jsdelivr.net/npm/@teamhanko/hanko-elements/dist/elements.js"; // import {all} from "https://cdn.jsdelivr.net/npm/@teamhanko/hanko-elements/dist/i18n/all.js"; // Change `apiUrl` to the URL where your Hanko-API instance is running. const apiUrl = "http://localhost:8000"; // Register Hanko Web Components const {hanko} = await register(apiUrl, {translations: all, sessionCheckInterval: 5000}); // Get DOM elements const hankoAuthEl = document.getElementById("hankoAuth"), hankoProfileEl = document.getElementById("hankoProfile"), hankoEventsEl = document.getElementById("hankoEvents"), logoutButtonEl = document.getElementById("logoutButton"), langSelectEl = document.getElementById("langSelect"), dialogEl = document.getElementById("dialog"), dialogContentEl = dialogEl.getElementsByTagName("div").item(0); // Function to show or hide individual elements function setVisibility(element, visible) { element.hidden = !visible; } // Function to show the authentication component or the profile component function showAuthComponent(showAuth) { setVisibility(hankoAuthEl, showAuth); setVisibility(hankoProfileEl, !showAuth); } // Function to show the dialog element function showDialog(message) { dialogContentEl.innerText = message; dialogEl.showModal(); } // Function to change the language of the Hanko web components function selectLanguage(lang) { hankoAuthEl.lang = lang; hankoProfileEl.lang = lang; } // Function to add event listeners function addEventListeners() { hankoEventsEl.addEventListener("onSessionCreated", () => { // The user has completed the authentication flow through the hanko-auth component, so we can display the // hanko-profile and hide the hanko-auth component. showAuthComponent(false); // Show profile component setVisibility(logoutButtonEl, true); // Show the logout button // When the dialog was initially opened due to the session expiring in the past, and it has not been closed // manually before re-authentication taking place in another browser window, close the dialog automatically. if (dialogEl.open) { dialogEl.close(); // Close the dialog when it is still open and a new session was created } }); hankoEventsEl.addEventListener("onSessionExpired", () => { // The session has expired, so we can show the dialog to notify the user. Additionally, the logout button // can be hidden. showDialog("Your session has expired"); // Show message on the overlay dialog setVisibility(logoutButtonEl, false); // Hide the logout button }); hankoEventsEl.addEventListener("onUserLoggedOut", () => { // The user has logged out, so we show the hanko-auth component and hide the profile element as well as the ``` -------------------------------- ### Enable Password Authentication Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Enable password-based authentication and set the minimum password length in the configuration file. ```yaml password: enabled: true min_password_length: 8 ``` -------------------------------- ### Set WebAuthn Relying Party Origins using Environment Variable Source: https://github.com/teamhanko/hanko/wiki/Using-environment-variables Configure the origins for WebAuthn relying parties. Multivalued options like arrays require comma-separated values. ```shell export SERVER_WEBAUTHN_RELYING_PARTY_ORIGINS="https://hanko.io,android:apk-key-hash:nLSu7w..." ``` -------------------------------- ### Handle Passkey Registration Source: https://github.com/teamhanko/hanko/blob/main/backend/flow_api/static/generic_client.html Handles passkey registration by creating a public key using the webauthnCreate function with the provided creation options. ```javascript const passkeyRegisterHandler = async (payload) => { document.getElementsByName("public_key")[0].value = await webauthnCreate(payload.creation_options) } ``` -------------------------------- ### Import Hanko Elements Register Function (CDN) Source: https://github.com/teamhanko/hanko/blob/main/frontend/elements/README.md Include a script tag to import the `register` function from the `hanko-elements` package hosted on a CDN. This is an alternative to using a module bundler. ```html ``` -------------------------------- ### Default Hanko Configuration File Source: https://github.com/teamhanko/hanko/wiki/Using-configuration-file This snippet shows the complete default configuration file for the Hanko backend, including all available options with their default settings. ```yaml account: allow_deletion: true allow_signup: true convert_legacy_config: false database: user: hanko password: hanko host: localhost port: "5432" dialect: postgres email: enabled: true optional: true acquire_on_registration: true acquire_on_login: false require_verification: true limit: 100 use_as_login_identifier: true max_length: 100 use_for_authentication: true passcode_ttl: 300 email_delivery: enabled: true from_address: noreply@hanko.io from_name: Hanko smtp: host: localhost port: "465" log: log_health_and_metrics: true passkey: enabled: true optional: false acquire_on_registration: always acquire_on_login: always attestation_preference: direct user_verification: preferred limit: 100 password: enabled: true optional: false acquire_on_registration: always acquire_on_login: never recovery: true min_length: 8 rate_limiter: enabled: true store: in_memory passcode_limits: tokens: 3 interval: 1m password_limits: tokens: 3 interval: 1m token_limits: tokens: 3 interval: 1m saml: enabled: false secrets: keys: - abcedfghijklmnopqrstuvwxyz server: public: cors: allow_origins: - http://localhost:63342 - http://localhost:8888 - http://localhost:8000 service: name: Hanko Authentication Service session: lifespan: 1h enable_auth_token_header: false third_party: providers: apple: enabled: false discord: enabled: false github: enabled: false google: enabled: false linkedin: enabled: false microsoft: enabled: false username: enabled: false optional: true acquire_on_registration: true acquire_on_login: true use_as_login_identifier: true min_length: 3 max_length: 32 webauthn: timeouts: registration: 60000 login: 60000 relying_party: id: localhost origins: - http://localhost:63342 - http://localhost:8888 - http://localhost:8000 webhooks: enabled: false allow_time_expiration: false ``` -------------------------------- ### Hanko Backend Database Configuration Source: https://github.com/teamhanko/hanko/blob/main/backend/README.md Configuration for connecting the Hanko backend to a database. Update placeholders with your specific database details. ```yaml database: user: password: host: localhost # change this if the DB is not running on localhost, esp. in a production setting port: database: dialect: # depending on your choice of DB: postgres, mysql ``` -------------------------------- ### Initialize Hanko and Redirect on Session Creation Source: https://github.com/teamhanko/hanko/blob/main/quickstart/public/html/unauthorized.html Use this snippet to initialize the Hanko Web Component and configure a redirect to a secured page when a user session is successfully created. The sessionCheckInterval option is set to 5000 milliseconds. ```javascript import { register } from "{{.HankoElementUrl}}"; const { hanko } = await register("{{.HankoUrl}}", { sessionCheckInterval: 5000 }); hanko.onSessionCreated(() => window.location.href = "/secured"); ```