A decentralized identifier (DID) is a URI of the form did:<method>:<method-specific-id> that resolves to a DID document: a JSON object listing public keys and the ways each key may be used. Whoever holds the matching private key can prove they control the DID, with no central identity provider issuing or approving the identifier.
That is the whole idea. Everything else (wallets, verifiable credentials, OpenID4VC) is built on top of “resolve an identifier to keys, then verify a signature”. This guide skips the blockchain narrative and works through the two methods you will actually meet first, did:key and did:web, with code you can run.
If you are coming from OAuth and OIDC, the mental model shift is this: in OIDC the relying party trusts an issuer because it fetched /.well-known/openid-configuration and the JWKS from a known URL. A DID generalises the same move. Instead of “trust this issuer URL”, the identifier itself tells you where (or how) to get the keys. Our OAuth 2.0 developer guide covers the issuer-centric model for contrast.
Anatomy of a DID and a DID document
did:web:example.com:users:alice
│ │ └──────────────────── method-specific identifier
│ └──────────────────────── method (how to resolve)
└───────────────────────────── scheme
Resolving it yields a DID document. A minimal one:
{
"@context": [
"https://www.w3.org/ns/did/v1",
"https://w3id.org/security/suites/jws-2020/v1"
],
"id": "did:web:example.com",
"verificationMethod": [
{
"id": "did:web:example.com#key-1",
"type": "JsonWebKey2020",
"controller": "did:web:example.com",
"publicKeyJwk": {
"kty": "OKP",
"crv": "Ed25519",
"x": "11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"
}
}
],
"authentication": ["did:web:example.com#key-1"],
"assertionMethod": ["did:web:example.com#key-1"]
}
Three properties matter in practice:
| Field | Purpose |
|---|---|
verificationMethod | The public keys, each with an id you can reference with a #fragment |
authentication | Keys allowed to prove “I am this DID” (login, challenge-response) |
assertionMethod | Keys allowed to sign claims, such as issuing a verifiable credential |
Separating the two purposes lets you keep a login key and an issuing key distinct, the same reason you separate signing and encryption keys in a JWKS.
did:key: the identifier is the public key
did:key needs no server. The public key is encoded straight into the identifier, so resolution is a pure function. Steps for Ed25519:
- Take the 32-byte raw public key.
- Prepend the multicodec prefix
0xed 0x01(Ed25519 public key). - Encode with base58btc.
- Prepend
z(the multibase marker for base58btc) anddid:key:.
Here is a complete, runnable implementation. It needs only the cryptography package (pip install cryptography):
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
from cryptography.hazmat.primitives import serialization
ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
def b58encode(data: bytes) -> str:
n = int.from_bytes(data, "big")
out = ""
while n:
n, r = divmod(n, 58)
out = ALPHABET[r] + out
pad = len(data) - len(data.lstrip(b"\0"))
return "1" * pad + out
def b58decode(s: str) -> bytes:
n = 0
for ch in s:
n = n * 58 + ALPHABET.index(ch)
body = n.to_bytes((n.bit_length() + 7) // 8, "big")
pad = len(s) - len(s.lstrip("1"))
return b"\0" * pad + body
ED25519_PREFIX = bytes([0xED, 0x01]) # multicodec: ed25519-pub
def did_key(public_raw: bytes) -> str:
return "did:key:z" + b58encode(ED25519_PREFIX + public_raw)
def resolve(did: str) -> bytes:
assert did.startswith("did:key:z")
raw = b58decode(did[len("did:key:z"):])
assert raw[:2] == ED25519_PREFIX, "not an Ed25519 did:key"
return raw[2:]
sk = Ed25519PrivateKey.generate()
pub = sk.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
did = did_key(pub)
print(did) # did:key:z6Mk...
sig = sk.sign(b"hello")
Ed25519PublicKey.from_public_bytes(resolve(did)).verify(sig, b"hello")
print("verified with key recovered from the DID alone")
Running it prints a did:key:z6Mk... identifier followed by the confirmation line. Note what happened: the verifier never contacted anything. It recovered the key from the identifier and checked the signature.
Where did:key fits: ephemeral identities, tests, device-to-device handshakes, and holder DIDs in wallets where you do not want to run infrastructure.
Where it does not: anything long-lived. The DID is the key, so rotating the key means a new DID. There is no revocation story beyond “stop trusting that DID”.
did:web: the identifier is a URL
did:web maps a DID to an HTTPS URL. The rules from the did:web method specification:
| DID | Resolves to |
|---|---|
did:web:example.com | https://example.com/.well-known/did.json |
did:web:example.com:users:alice | https://example.com/users/alice/did.json |
did:web:localhost%3A3000 | https://localhost:3000/.well-known/did.json |
Each : after the domain becomes /, and a port colon is percent-encoded as %3A. Resolution is a plain GET:
curl -s https://example.com/.well-known/did.json | jq '.verificationMethod[0]'
A tiny resolver in Python, with the checks people forget:
import json, urllib.parse, urllib.request
def did_web_url(did: str) -> str:
assert did.startswith("did:web:")
parts = did[len("did:web:"):].split(":")
host = urllib.parse.unquote(parts[0]) # decodes %3A in ports
path = "/".join(parts[1:]) + "/did.json" if len(parts) > 1 else ".well-known/did.json"
return f"https://{host}/{path}"
def resolve_did_web(did: str) -> dict:
with urllib.request.urlopen(did_web_url(did), timeout=5) as r:
doc = json.load(r)
if doc.get("id") != did: # the document must name itself
raise ValueError(f"DID document id {doc.get('id')} does not match {did}")
return doc
The id comparison is not optional. Without it, a server can answer a request for did:web:a.example with a document that claims to be some other DID.
Hosting did.json on a static site
Because this is just a file, any static host works. On a Hugo site like this one, drop it in static/.well-known/did.json. Serve it as application/did+json or application/json and allow cross-origin reads if browser wallets will fetch it:
location = /.well-known/did.json {
default_type application/json;
add_header Access-Control-Allow-Origin *;
add_header Cache-Control "public, max-age=300";
}
Keep the cache lifetime short. It is your key-revocation latency: a compromised key stays trusted for as long as verifiers hold a cached copy.
The trust model, side by side
| did:key | did:web | OIDC issuer + JWKS | |
|---|---|---|---|
| Key discovery | Decoded from the identifier | HTTPS GET of did.json | HTTPS GET of discovery + jwks_uri |
| Key rotation | Impossible (new DID) | Edit the file | Publish new kid in JWKS |
| Trust anchor | The key itself | DNS + TLS certificate | DNS + TLS certificate |
| Revocation | None | Remove the key; wait out caches | Remove the key; wait out caches |
| Infrastructure | None | A web server | An authorization server |
The uncomfortable row is did:web trust. It is exactly as strong as your DNS registrar account and TLS issuance, the same as an OIDC issuer. “Decentralized” describes who controls the identifier (you, not a platform), not a stronger root of trust. If an attacker takes over the domain, they take over the DID. Protect it accordingly, and monitor Certificate Transparency logs for the domain.
Signing and verifying with a DID
A DID becomes useful when it identifies the signer. The common pattern is a JWT whose iss is the DID and whose header kid points at the verification method:
{ "alg": "EdDSA", "typ": "JWT", "kid": "did:web:example.com#key-1" }
Verification then follows four steps:
- Parse
kid, split at#to get the DID and the fragment. - Resolve the DID to its document and check
document.idequals the DID. - Find the
verificationMethodwhoseidequals the fullkid, and confirm it appears under the relationship you need (authenticationfor login,assertionMethodfor issued claims). - Verify the signature with that key, then validate
iss,aud,expas usual.
Step 3 is where relationship checks stop a key authorised only for authentication from being used to issue credentials. This is also where the JWT algorithm confusion attack bites: pin the expected alg from the verification method’s key type (OKP/Ed25519 means EdDSA) and never trust the alg header alone. You can inspect any token you produce with the JWT Decoder.
From DIDs to verifiable credentials
A DID alone proves control of a key. A verifiable credential (VC) is a signed claim about a subject, where the issuer and subject are identified by DIDs:
{
"@context": ["https://www.w3.org/ns/credentials/v2"],
"type": ["VerifiableCredential", "EmployeeCredential"],
"issuer": "did:web:hr.example.com",
"validFrom": "2026-11-17T00:00:00Z",
"credentialSubject": {
"id": "did:key:z6MkshGPe88dyiuSrgxV2P7GVHL3KgCp9k4i2fWNz86G9Dw4",
"department": "Engineering"
}
}
The issuer signs with a key from its assertionMethod; the holder (a wallet) stores it and later presents it. Verifiers resolve the issuer DID and check the signature, and they never call the issuer, which is the “decentralized” part in the useful sense: no per-verification round-trip to the issuing system.
When to use a DID, and when OIDC is still the better tool
Use DIDs when:
- Issuer and verifier have no prior relationship, so you cannot pre-register a client or exchange metadata.
- The credential travels with the user (a wallet) rather than being fetched live from an identity provider.
- You need pairwise identifiers, a fresh
did:keyper relying party to prevent correlation.
Stay with OIDC, SAML or passkeys when:
- You are authenticating employees or customers to your own applications. A session, revocation and consent model already exists, and Keycloak gives it to you.
- You need immediate, centrally enforced revocation. A DID ecosystem offers only short caches and status lists.
- Your users have no wallet. Passkeys (adoption guide) deliver phishing resistance with far less ecosystem to build.
Production checklist
- Pin the method allow-list. Accept
did:webanddid:keyonly. Resolving arbitrary methods opens SSRF-style fetches and unmaintained resolver code. - Block private address space when resolving
did:web. A DID ofdid:web:169.254.169.254ordid:web:localhostshould not make your server fetch internal endpoints. - Require HTTPS and verify certificates. Never fall back to HTTP.
- Cap response size and timeout (a few KB and 5 seconds are plenty for a DID document).
- Check
document.idequals the requested DID, every time. - Check the verification relationship (
authenticationvsassertionMethod) for the operation. - Cache with a short TTL and re-resolve on signature failure before rejecting.
What to read next
The W3C DID Core specification defines the data model; each method (did:web, did:key) has its own short spec; and the DID Resolution spec defines the resolver interface.





