# OpenID Connect (Authorization Code + PKCE)

The OIDC Authorization Code flow with PKCE end to end, using plain HTTP and curl, so you understand every step before reaching for a library.

This guide walks the **Authorization Code flow with PKCE** using nothing but HTTP, so you can see exactly what each step sends and receives. The Node and React guides do the same thing with a library; read this one first.

Make sure you have registered an application and a redirect URI as described in [Before you start](https://dts-identity.com/docs/quickstarts.md#before-you-start).

## The flow in one picture

1. Your app redirects the browser to the **authorization endpoint** with a PKCE challenge.
2. The user signs in; the platform redirects back to your **redirect URI** with a one-time `code`.
3. Your app exchanges the `code` (plus the PKCE verifier) at the **token endpoint** for an ID token and access token.
4. Your app validates the ID token and, optionally, calls the **UserInfo endpoint**.

## 1. Create a PKCE verifier and challenge

Generate a random **code verifier**, then derive its SHA-256 **code challenge**:

```bash tab="Shell" tab-group="lang"
# code verifier: 43-128 chars of unreserved characters
CODE_VERIFIER=$(openssl rand -base64 60 | tr -d '\n=+/' | cut -c1-64)

# code challenge: base64url(SHA256(verifier))
CODE_CHALLENGE=$(printf '%s' "$CODE_VERIFIER" | openssl dgst -binary -sha256 | openssl base64 | tr '+/' '-_' | tr -d '=\n')

echo "verifier:  $CODE_VERIFIER"
echo "challenge: $CODE_CHALLENGE"
```

```js tab="Node.js" tab-group="lang"
import { createHash, randomBytes } from 'node:crypto';

const codeVerifier = randomBytes(48).toString('base64url'); // 64 chars
const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');

console.log('verifier: ', codeVerifier);
console.log('challenge:', codeChallenge);
```

```python tab="Python" tab-group="lang"
import base64, hashlib, secrets

code_verifier = secrets.token_urlsafe(48)  # 64 chars
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()

print("verifier: ", code_verifier)
print("challenge:", code_challenge)
```

```java tab="Java" tab-group="lang"
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;

var random = new byte[48];
new SecureRandom().nextBytes(random);
var encoder = Base64.getUrlEncoder().withoutPadding();

var codeVerifier = encoder.encodeToString(random); // 64 chars
var codeChallenge = encoder.encodeToString(
    MessageDigest.getInstance("SHA-256").digest(codeVerifier.getBytes(StandardCharsets.US_ASCII)));

System.out.println("verifier:  " + codeVerifier);
System.out.println("challenge: " + codeChallenge);
```

```csharp tab="C#" tab-group="lang"
using System.Security.Cryptography;
using System.Text;

static string B64Url(byte[] bytes) =>
    Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');

var codeVerifier = B64Url(RandomNumberGenerator.GetBytes(48)); // 64 chars
var codeChallenge = B64Url(SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier)));

Console.WriteLine($"verifier:  {codeVerifier}");
Console.WriteLine($"challenge: {codeChallenge}");
```

```go tab="Go" tab-group="lang"
import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
)

random := make([]byte, 48)
rand.Read(random)

codeVerifier := base64.RawURLEncoding.EncodeToString(random) // 64 chars
sum := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(sum[:])

fmt.Println("verifier: ", codeVerifier)
fmt.Println("challenge:", codeChallenge)
```

```php tab="PHP" tab-group="lang"
function b64url(string $bytes): string {
    return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}

$codeVerifier = b64url(random_bytes(48)); // 64 chars
$codeChallenge = b64url(hash('sha256', $codeVerifier, true));

echo "verifier:  $codeVerifier\n";
echo "challenge: $codeChallenge\n";
```

```rust tab="Rust" tab-group="lang"
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use rand::RngCore;
use sha2::{Digest, Sha256};

let mut random = [0u8; 48];
rand::thread_rng().fill_bytes(&mut random);

let code_verifier = URL_SAFE_NO_PAD.encode(random); // 64 chars
let code_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes()));

println!("verifier:  {code_verifier}");
println!("challenge: {code_challenge}");
```

Keep the verifier for step 3. Also generate a random `state` (and, if you check it, a `nonce`) to protect against cross-site request forgery and replay.

## 2. Send the user to the authorization endpoint

Open this URL in the browser (line-wrapped here for readability):

```
https://<your-domain>/authorize
  ?response_type=code
  &client_id=<your-client-id>
  &redirect_uri=https://app.example.com/callback
  &scope=openid%20profile%20email%20offline_access
  &state=<random-state>
  &code_challenge=<CODE_CHALLENGE>
  &code_challenge_method=S256
```

- `scope` must include `openid`. Add `profile` and `email` for the standard claims, and `offline_access` if you want a refresh token.
- After the user signs in, the platform redirects to
  `https://app.example.com/callback?code=<one-time-code>&state=<random-state>`.
- **Check that the returned `state` matches** the one you sent before continuing.

## 3. Exchange the code for tokens

Post the code and the PKCE verifier to the token endpoint.

For a **confidential** client, authenticate with the client secret (HTTP Basic shown here):

```bash
curl -X POST https://<your-domain>/oauth/token \
  -u '<your-client-id>:<your-client-secret>' \
  -d grant_type=authorization_code \
  -d redirect_uri=https://app.example.com/callback \
  -d code=<one-time-code> \
  -d code_verifier=$CODE_VERIFIER
```

For a **public** client (no secret), send the `client_id` as a form field and rely on PKCE:

```bash
curl -X POST https://<your-domain>/oauth/token \
  -d grant_type=authorization_code \
  -d client_id=<your-client-id> \
  -d redirect_uri=https://app.example.com/callback \
  -d code=<one-time-code> \
  -d code_verifier=$CODE_VERIFIER
```

The response contains the tokens:

```json
{
  "access_token": "<jwt>",
  "id_token": "<jwt>",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "<token>",
  "scope": "openid profile email offline_access"
}
```

A `refresh_token` is present only if you requested `offline_access` and the application is allowed to receive one.

## 4. Validate the ID token

The **ID token** is a JWT that proves who signed in. Validate it before you trust it:

- Verify the signature against the platform's signing keys at `/.well-known/jwks`.
- Check `iss` matches your instance, `aud` matches your client ID, and the token is not expired (`exp`).
- If you sent a `nonce`, check it matches.

The `sub` claim is the stable user identifier; `profile` and `email` scopes add claims such as `name` and `email`.

## 5. Call UserInfo (optional)

For claims beyond the ID token, call the UserInfo endpoint with the access token:

```bash
curl https://<your-domain>/userinfo \
  -H 'Authorization: Bearer <access_token>'
```

## 6. Log the user out (optional)

To end the session, send the user to the end-session endpoint:

```
https://<your-domain>/logout
  ?id_token_hint=<id_token>
  &post_logout_redirect_uri=https://app.example.com/
```

Register the `post_logout_redirect_uri` on your application first, the same way you register a redirect URI.

## Troubleshooting

- **`redirect_uri` mismatch.** The `redirect_uri` in steps 2 and 3 must be identical to each other and to a value registered on the application, compared character by character (scheme, host, port, path, trailing slash).
- **`invalid_grant` at the token endpoint.** The code is single-use and short-lived; request a fresh one. This also appears if the `code_verifier` does not match the `code_challenge` you sent.
- **`invalid_client`.** The client authentication is wrong: a confidential client must send its secret; a public client must not, and must be registered as a public (PKCE) client.

## Next

- [Node / Express backend](https://dts-identity.com/docs/quickstarts/node-express.md) does this with a library.
- [Python / Flask backend](https://dts-identity.com/docs/quickstarts/python-flask.md) does the same in Python.
- [React single-page app](https://dts-identity.com/docs/quickstarts/react-spa.md) does it in the browser.
