Skip to content

Search Sweden Sites

Popular searches

Shortcuts

Can’t find what you’re looking for?

Go to the search page

BankID on your website

How to add login and signing with BankID – step by step, with ready-made code examples.

How it works

Your visitor logs in with BankID on your website in four steps. You add a button, we take care of the rest.

  1. 1The visitor clicksthe BankID button on your website.
  2. 2Approves in the BankID appby scanning the QR code, or directly on the phone.
  3. 3Your website gets a codeas proof that someone approved. The code does not say who.
  4. 4Your server asks us whoand gets the name and identity number back. Done!

What you need

  • Site keyYour website’s id with us.
  • Secret keyA password only your server knows.
  • Your domainAdded to the list, for example www.example.com.

Everything is in My pages → BankID. Get your keys →

Would you rather have us connect BankID for you? Contact us

Get started

It takes three steps. You paste a snippet into your web page, receive an answer when the person is done, and let your server ask us who it was.

Step 1: Add the BankID button

Paste this on the page where the button should be. Replace YOUR_SITE_KEY with your site key from My pages, and the address with the page the person should land on afterwards.

[[tabs: HTML]]

<link rel="stylesheet" href="https://authentication.swedensites.com/sdk/v1/bankid-sdk.min.css">
<script src="https://authentication.swedensites.com/sdk/v1/bankid-sdk.min.js"
        data-site-key="YOUR_SITE_KEY"
        data-redirect-url="https://www.example.com/logged-in/"></script>

<button type="button" class="bankid-signin-btn">Log in with BankID</button>

That is all the web page needs. The button opens the BankID window, which shows a QR code on a computer and opens the BankID app directly on a phone.

Step 2: The person approves

The person approves in the BankID app. Then the browser is sent on to the address you gave, with a code at the end:

https://www.example.com/logged-in/?bankid_auth_token=3f2a…c91e

The code is called a token. It says nothing about who the person is. It is a ticket your server cashes in in the next step.

Step 3: Your server asks who it was

On the page the person lands on, your server reads the code and asks us who it was. Pick the language your website is written in:

[[tabs: PHP | Node.js | curl]]

<?php
$token  = $_GET['bankid_auth_token'] ?? '';
$body   = json_encode(['token' => $token, 'sitekey' => 'YOUR_SITE_KEY', 'ts' => time(), 'nonce' => bin2hex(random_bytes(16))]);
$secret = getenv('BANKID_SECRET_KEY');   // your secret key – never in the web page

$ch = curl_init('https://authentication.swedensites.com/bankid/verify/');
curl_setopt_array($ch, [
    CURLOPT_POST => true, CURLOPT_POSTFIELDS => $body, CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-SS-Signature: ' . hash_hmac('sha256', $body, $secret)],
]);
$answer = json_decode((string) curl_exec($ch), true);

if (($answer['status'] ?? '') === 'ok') {
    // Logged in! $answer['givenname'], $answer['surname'], $answer['ssn'] (identity number)
} else {
    // Not logged in – show an error
}
// Node.js 18 or later
import crypto from 'node:crypto';

const token = req.query.bankid_auth_token;
const body = JSON.stringify({ token, sitekey: 'YOUR_SITE_KEY', ts: Math.floor(Date.now() / 1000), nonce: crypto.randomUUID() });
const secret = process.env.BANKID_SECRET_KEY;   // your secret key – never in the web page

const answer = await fetch('https://authentication.swedensites.com/bankid/verify/', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json', 'X-SS-Signature': crypto.createHmac('sha256', secret).update(body).digest('hex') },
  body,
}).then((r) => r.json());

if (answer.status === 'ok') {
  // Logged in! answer.givenname, answer.surname, answer.ssn (identity number)
} else {
  // Not logged in – show an error
}
# To try it from a terminal. Set TOKEN, SITE_KEY and SECRET_KEY first.
BODY=$(printf '{"token":"%s","sitekey":"%s","ts":%d,"nonce":"%s"}' "$TOKEN" "$SITE_KEY" "$(date +%s)" "$(openssl rand -hex 16)")
SIG=$(printf '%s' "$BODY" | openssl dgst -sha256 -hmac "$SECRET_KEY" | sed 's/^.* //')
curl -s https://authentication.swedensites.com/bankid/verify/ \
  -H 'Content-Type: application/json' -H "X-SS-Signature: $SIG" -d "$BODY"

The answer looks like this when everything went well:

{ "status": "ok", "givenname": "Anna", "surname": "Andersson", "ssn": "199001011234", "verid": "SSV-4F1C0B9E…" }

Done. The person is logged in on your website.

Keys and domains

Everything you need is in My pages → BankID.

What it is Where it is used
Site key Your website’s id with us. It is not secret. In the button’s code (step 1) and in your server’s question (step 3).
Secret key A password for your server. Only on your server (step 3). Never put it in the web page’s code, in an app or in git.
Domains The addresses where the button may work, for example www.example.com. BankID only starts on the domains in the list.

Two things about the domains: example.com and www.example.com count as two different ones, so add both if the site has both. If you test on your own computer, add localhost with the port number, for example localhost:3000.

Test before you go live

You get two sets of keys: one for test and one for live. My pages shows which is which. The code is the same, only the keys differ.

  • The test key logs in with a test BankID, not your real one. How to get one and set the BankID app up for test is described on demo.bankid.com.
  • The live key is used when real people log in with their own BankID.

Build and try with the test key. Switch to the live key when everything works.

Customise the BankID button

You change how BankID behaves by adding more data- lines to the script tag from step 1.

Line What it does
data-site-key="…" Your site key. Required.
data-redirect-url="…" The page the person is sent to when done.
data-lang="en" The BankID window in English. Without the line it follows the page’s language.
data-method="qr" Always show a QR code, also on a phone. sameDevice always opens the app on the same device. Without the line the best one is chosen automatically.
data-mode="sign" Signing instead of login, see the next section.
data-block-app="true" Asks the person to open the page in a normal browser if it was opened inside Facebook, Messenger or Instagram, where BankID does not work well.

Every element with the class bankid-signin-btn starts BankID, so you can have several buttons and style them any way you like.

Let someone sign

If you want the person to approve a text, for example an agreement, add two lines:

[[tabs: HTML]]

<script src="https://authentication.swedensites.com/sdk/v1/bankid-sdk.min.js"
        data-site-key="YOUR_SITE_KEY"
        data-mode="sign"
        data-user-visible-data="I approve agreement 2026-1182 with Example Ltd."
        data-redirect-url="https://www.example.com/signed/"></script>

The text is shown in the BankID app before the person approves. Write it so that it can be understood on its own.

Steps 2 and 3 are exactly as for login. Keep verid from the answer together with the text that was signed. It is your receipt for the signing.

If something goes wrong

Answers to your server (step 3)

If status is not ok, the person must not be let in. Common reasons:

status What it means Do this
invalid signature The secret key does not match. Check that you have the right secret key for the right site key.
timestamp invalid Your server’s clock is wrong. Set the server’s clock right (more than 5 minutes off is enough).
no session found The code is unknown or already used. Each code can only be used once. Let the person log in again.
session not complete The person has not approved. Let the person log in again.
invalid sitekey, wrong sitekey Wrong site key. Use the same site key as in the button.

All error codes are in Reference for developers.

In the BankID window

If the person cancels, or time runs out, the BankID window shows a message and a button to try again by itself. You do not need to do anything.

  • The person cancelled in the BankID app.
  • Time ran out. A login must be approved within 3 minutes.
  • BankID did not start. Usually the app is missing or needs updating.
  • The BankID is not valid. The person needs to renew their BankID with their bank.
  • “No valid BankID site key” or “The BankID process could not be started” usually means the site key is missing or the domain is not in the list in My pages.

Security

Five rules that keep your login secure:

  1. Always ask us from your server (step 3). Only when the answer is ok is the person logged in. Never just trust that the browser came back with a code.
  2. Keep the secret key secret. It should only be on your server. If it has leaked, contact us and we will replace it.
  3. Only add your own domains in My pages.
  4. Only keep what you need about the person. Say in your privacy policy that you use BankID.
  5. Each code works once. That way nobody can reuse someone else’s login.

We keep every login and signing (identity number, name, time, IP address and signed text) for 24 months, as our privacy policy says.

Reference for developers

You do not need this to get started. It is for you who want to control BankID from JavaScript or build your own interface.

Settings in JavaScript

Everything in Customise the BankID button can also be given with SSBankID.init(). Then you can receive the result in your own code instead of sending the person on:

[[tabs: JavaScript]]

SSBankID.init({
  siteKey: 'YOUR_SITE_KEY',
  lang: 'en',                // 'sv' or 'en'
  method: 'auto',            // 'auto', 'qr' or 'sameDevice'
  mode: 'auth',              // 'auth' or 'sign'
  userVisibleData: null,     // the text to sign when mode is 'sign'
  onComplete: (data) => {    // replaces redirectUrl
    fetch('/my-server/bankid', { method: 'POST', body: JSON.stringify({ token: data.token }) });
  },
  onError: (reason, data) => console.warn('BankID:', reason),
  onEvent: (status, data) => console.log(status),
});

In data- attributes the functions are given by name: data-on-complete="myApp.done", data-on-error, data-on-event.

Method What it does
SSBankID.init(settings) Sets the settings. Can be called several times.
SSBankID.start() Starts BankID, like a click on the button.
SSBankID.on(event, function) Listens to an event, see below.
SSBankID.close() Closes the BankID window.
Event When
usersign The person has opened the login in the BankID app and is to enter their security code.
complete The person has approved. Data: { status, token }.
failed The login was cancelled or failed. Data: { status, reason }.

reason is BankID’s reason in lowercase: usercancel (the person cancelled), expiredtransaction (time ran out), cancelled (a new login was started), startfailed (the app did not start), certificateerr (the BankID is not valid), userdeclinedcall. Treat unknown values as a general error.

Your server’s question in detail

POST https://authentication.swedensites.com/bankid/verify/

Part What
token The code from step 2.
sitekey Your site key.
ts The time now, in seconds since 1970 (Unix time). May differ at most 5 minutes from our clock.
nonce A random value. Optional but recommended.
Header X-SS-Signature HMAC-SHA256 of the whole JSON text with your secret key, in lowercase hex. Compute it on exactly the text you send.
Field in the answer What
status ok, or an error code.
givenname, surname Given names and surname according to BankID (all given names).
ssn Swedish personal identity number, 12 digits.
verid Our id for this very login. Good to keep as a receipt.

The answer always has HTTP status 200, so read status. All error codes: invalid json, missing parameters, timestamp invalid, missing signature, invalid sitekey, secret not configured (contact us), invalid signature, no session found, wrong sitekey, session not complete.

Building your own interface

If you do not want to use the BankID window, for example in an app, you can call the same addresses as the button. The calls must come from a browser on one of your domains.

Address What it does
POST /bankid/entry/ Starts. Send { "k": site key, "device": "qr" or "same", "mode": "auth" or "sign", "userVisibleData": text }. The answer has auth_token and either qr_image (an image address) or auto_start_token.
GET the address in qr_image The QR code as an image. Fetch it again every other second with ?t=<time> at the end. 410 when it has expired.
bankid:///?autostarttoken=… Opens the BankID app on the same device, with auto_start_token.
GET /bankid/sse/?token=<auth_token> Status in real time (Server-Sent Events): usersign, complete with token, or failed with reason. Use EventSource; it reconnects by itself between the steps.
POST /bankid/cancel/ Cancels. Send { "token": auth_token, "sitekey": site key }.

Every address is on https://authentication.swedensites.com. If entry does not start, it returns a status that says why, for example host not allowed when the domain is not in the list.

Limits

A login must be approved within 3 minutes
A code (token) can be used once
ts may differ from our clock at most 5 minutes
We keep logins and signings 24 months

Versions

You are using version 1 (/sdk/v1/). Changes that could affect your website come in a new version with a new address, and version 1 stays. Fixes come in version 1 without you needing to change anything.

Help

Stuck? Write to info@swedensites.com and tell us which site key it concerns. Never send your secret key.

Cookie settings

Choose which cookies we may use. You can change your mind at any time under Cookie settings at the bottom of the page.

Read more in our cookie policy

Would you like to start the chat?

To use the chat, you need to accept the cookies the chat needs to work.

Read more in our cookie policy and privacy policy.

AI summary

The reply is written by AI based on this entry. Check important details with us.