# OpenID Connect: ID Tokens, Userinfo and Access Tokens — Authentication & Authorization

Source: https://www.skillbyai.com/en/authentication/o-oidc

> Login is not the same as API access.

## Who logged in versus what may be called

OAuth 2.0 alone is about **authorization**; it does not tell the client who the user is. **OpenID Connect (OIDC)** adds an identity layer: request the `openid` scope and the token response includes an **ID token**, a JWT whose audience is the **client**, with claims such as `iss`, `sub` (stable user ID at that issuer), `aud`, `exp`, `iat`, `auth_time` and the `nonce` you sent. The client validates it to log the user in. The **access token** is meant for the **resource server** (API); clients should treat it as opaque and must not use it as proof of login. The **userinfo endpoint** returns profile claims when called with the access token. Identify users by the pair (`iss`, `sub`), not by email, which can change or be reused. Providers publish their endpoints and keys at `/.well-known/openid-configuration`.

## Validating an ID token in the client

jose library; values are examples.

```typescript
import { createRemoteJWKSet, jwtVerify } from 'jose';

const ISSUER = 'https://auth.example.com';
const JWKS = createRemoteJWKSet(new URL(`${ISSUER}/.well-known/jwks.json`)); // from discovery doc

export async function loginFromIdToken(idToken: string, expectedNonce: string) {
  const { payload } = await jwtVerify(idToken, JWKS, {
    issuer: ISSUER,
    audience: 'web-app',        // the ID token is addressed to THIS client
    algorithms: ['RS256', 'ES256'],
  });
  if (payload.nonce !== expectedNonce) throw new Error('nonce mismatch');

  // stable identity key: issuer + subject, not email
  return db.users.upsertByExternalId({ iss: payload.iss!, sub: payload.sub!,
    email: payload.email_verified ? String(payload.email) : undefined });
}
```

## Use a certified library

OIDC has many details (nonce, state, discovery, key rotation, logout). Prefer a certified client library or your framework's integration over hand-rolled code; the OpenID Foundation lists certified implementations.

**Quiz:** Who is the intended audience of an OIDC ID token?

- [ ] Any service in the same company
- [ ] The resource server (API)
- [ ] The user's browser extensions
- [x] The client application that requested the login

*Answer:* The client application that requested the login. APIs should receive access tokens; ID tokens prove login to the client.
