# Single sign-on protocols for SAP landscapes: SAML, OpenID Connect, Kerberos and certificates

> What SAML 2.0, OpenID Connect, Kerberos and X.509 certificates each do, which SAP component uses which, and how to read a failed login back to its cause.

- Course: Orchestrate, Unit 27 · Security, identity and compliance
- Page: https://erpfde.com/topics/single-sign-on-protocols/
- Updated: 2026-12-01
- Reading time: Foundational 8 min, Deep 40 min

Independent learning resource. Not affiliated with, sponsored by or endorsed by SAP SE. SAP and other SAP products mentioned are trademarks of SAP SE in Germany and other countries.

## Foundational layer

### The 60-second version

**Single sign-on** means a person proves who they are once, at one trusted place, and every application accepts that proof instead of asking for its own password. The trusted place is an **identity provider**; the application that relies on it is a **service provider** or **relying party**.

Four mechanisms carry that proof in an SAP landscape:

- **SAML 2.0**: the identity provider hands the browser a signed XML document, an *assertion*, that says "this is user X, for application Y, valid for the next few minutes". Most SAP web applications, including S/4HANA's launchpad, accept it.
- **OpenID Connect**: the same idea in a newer, lighter form. The proof is a signed *ID token* in JSON. SAP's cloud services, BTP applications and the identity tenant itself prefer it.
- **Kerberos**: the Windows sign-in on a company PC already produced a *ticket*. Applications on the corporate network can accept that ticket, so the person never sees a login screen. SAP GUI uses it through SAP's secure network layer.
- **X.509 certificates**: a certificate installed on a device or smart card proves the holder's identity, with no password at all. Useful for shared kiosks and machines.

Every one of them fails the same few ways: the wrong sender, a seal nobody trusts any more, a proof meant for another application, a clock that's off, or a name the application can't match to a user. Knowing that short list turns a vague "I can't log in" into a fix in minutes.

### Why it matters to the business

**Sign-in problems are expensive tickets.** One wrong setting stops a whole team, and help desks often reset passwords that were never the problem. A planner whose PC clock drifted nine minutes can lose a morning.

**Certificate changes cause outages.** Identity providers sign their proofs with certificates that expire and get replaced. If the identity team switches before every application trusts the new certificate, everyone using those applications is locked out at once.

**Partners and machines sign in too.** Distributors use a portal; a test bench kiosk signs a technician in with a certificate. Each needs its own route, and each route can break on its own.

**AI agents inherit it.** An agent that acts for a person needs that person's identity carried through to SAP, so SAP's own authorization checks still apply. That identity starts with a sign-in through these protocols.

**Example:** at Calder Pumpworks, the course's fictional pump maker, ten sign-in tickets arrived on Tuesday 1 December 2026. One was a control case that worked; the other nine had six different causes, from an expired kiosk certificate to a test system configured with production's name. The deep layer reads each one back to its cause. The tickets are synthetic course data.

### How SAP does it

As of 1 December 2026, SAP's documentation describes these routes:

- **The identity tenant in the middle.** SAP Cloud Identity Services' Identity Authentication acts as the identity provider for SAP applications and as a proxy to the company's own provider, such as Microsoft Entra ID. SAP Learning calls OpenID Connect the recommended protocol for integrating SAP cloud applications with it, while SAML 2.0 remains widely used ([SAP Learning](https://learning.sap.com/courses/introducing-sap-cloud-identity-services/describing-the-standards-for-authentication-and-provisioning_af14db99-1815-4e30-9dde-e14d2a76815e)). The [Cloud Identity Services topic](https://erpfde.com/topics/sap-cloud-identity-services/) covers the tenant itself.
- **SAP BTP.** A subaccount trusts the tenant over OpenID Connect, with no metadata files to swap, and one tenant per subaccount on this route ([SAP BTP](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/establish-trust-and-federation-between-sap-authorization-and-trust-management-service-a-161f8f0.md)).
- **S/4HANA and other ABAP systems in the browser.** The ABAP server acts as a SAML 2.0 service provider, set up in transaction `SAML2` ([SAP Help](https://help.sap.com/saphelp_em92/helpdata/en/4a/b4c93185376d61e10000000a42189c/content.htm)). It can also accept Kerberos through SPNEGO and X.509 client certificates.
- **SAP GUI.** Single sign-on runs through Secure Network Communications (SNC) with Kerberos or X.509 certificates. SAP's help pages say the SAP Single Sign-On product needed for this, and for Kerberos in the browser on ABAP, requires additional licences ([SAP Help](https://help.sap.com/saphelp_em92/helpdata/en/7c/82ea543d864dacb24f371f6655dccd/content.htm)). SAP also sells **SAP Secure Login Service for SAP GUI**, a cloud service that issues short-lived X.509 certificates for SAP GUI sign-in ([sap.com](https://www.sap.com/uk/products/financial-management/secure-login-service-for-gui.html)).

> **Note** **For functional consultants.** Sign-in setup rarely changes a process, but it changes testing. Test users must sign in the way real users will (through the identity tenant, not a local password), or UAT passes and go-live fails. When a test system is copied from production, ask whether its sign-in settings were copied too: a test system carrying production's name is one of the cases in this topic.

### Which protocol where

| Situation | Protocol | What the person sees | Who usually owns the fix |
| --- | --- | --- | --- |
| S/4HANA launchpad in a browser | SAML 2.0 from the identity tenant | Nothing, or the company sign-in page once a day | Identity team and SAP Basis |
| BTP applications, Joule, SAP cloud products | OpenID Connect from the identity tenant | Same company sign-in page | Identity team and the app team |
| Identity tenant to the company's own provider | OpenID Connect or SAML 2.0 | The company's usual sign-in and multifactor prompt | Identity team and the corporate directory team |
| SAP GUI on a company PC | Kerberos or certificates through SNC | No password prompt | SAP Basis and desktop support |
| Browser on the corporate network, no prompt at all | Kerberos through SPNEGO | No sign-in page | Directory team and SAP Basis |
| Shared kiosk or machine | X.509 client certificate | Tap or no action | Whoever runs the company's certificates |

### Questions to ask

- Which protocol does each of our SAP applications use to sign people in, and who owns each trust setting?
- When the identity provider's signing certificate is replaced, what is the order of steps, and who checks that every application trusts the new one first?
- What does each application receive as the user's name (login name, e-mail, global user ID), and what happens when an e-mail address changes?
- Are our servers' and PCs' clocks synchronised, and who is alerted when one drifts?
- Do we license SAP Single Sign-On or the Secure Login Service for SAP GUI, or are SAP GUI users still typing passwords?
- Which certificates expire in the next 90 days, and who renews them?
- Are test systems' sign-in settings separate from production's?

### Common misconceptions

- **"SAML and OpenID Connect are competitors; we must pick one."** Most landscapes run both: the identity tenant speaks SAML to some applications and OpenID Connect to others.
- **"Single sign-on makes us less secure."** Done right, it moves every password and multifactor check to one well-guarded place, and leavers lose access everywhere at once.
- **"A login error means a password problem."** Most single sign-on failures are trust settings, certificates, clocks or name mapping. Resetting the password fixes none of them.
- **"Kerberos for SAP GUI comes with the system."** SAP's help pages say SNC single sign-on with SAP Single Sign-On needs additional licences.
- **"A certificate is set up once."** Certificates expire by design. Without an owner and a renewal date, the outage is already scheduled.

### Key terms

- **Identity provider:** the trusted service that signs a person in and vouches for them, such as SAP Cloud Identity Services or Microsoft Entra ID.
- **Service provider (relying party):** the application that accepts the identity provider's proof instead of checking a password itself.
- **SAML 2.0:** an XML-based standard in which the identity provider sends a signed assertion through the browser.
- **OpenID Connect:** an identity layer on OAuth 2.0 in which the identity provider issues a signed ID token in JSON.
- **Kerberos:** a network sign-in protocol in which a key distribution center, usually Active Directory, issues tickets.
- **SPNEGO:** the way a browser offers a Kerberos ticket to a web server.
- **SNC (Secure Network Communications):** SAP's layer for signing in and encrypting SAP GUI and RFC connections.
- **X.509 certificate:** a signed electronic document binding a name to a key, issued by a certificate authority.
- **Trust:** the stored settings with which a service provider recognises an identity provider: its name, endpoints and certificates.

### Check yourself

1. What does single sign-on change for the person signing in?
   - A. They get a separate, stronger password for each SAP application they use daily
   - B. They prove who they are once, and each application accepts that proof
   - C. They no longer need any sign-in when working from home
   - D. Their SAP roles are copied from the identity provider each time

   Answer: B. An identity provider checks the person once and vouches for them; each application relies on that proof instead of its own password. Roles and remote access are separate questions.

2. Calder's identity team replaces the identity provider's signing certificate, and within minutes everyone using S/4HANA is locked out. What most likely went wrong?
   - A. The new certificate used a weaker signing algorithm than the old one did
   - B. The users' passwords expired at the same moment
   - C. S/4HANA didn't yet trust the new certificate when the switch happened
   - D. The identity provider ran out of sign-in licences

   Answer: C. A service provider accepts only proofs sealed with a certificate it trusts. The safe order is to make every application trust the new certificate first, then switch; SAP lets the certificate be chosen per application for exactly this reason.

3. Which mechanism lets a person on a company PC open SAP GUI without any password prompt?
   - A. A SAML assertion sent through the browser
   - B. An OpenID Connect ID token stored in SAP GUI
   - C. A shared technical user configured on the PC
   - D. Kerberos or a certificate carried through SNC

   Answer: D. SAP GUI is not a browser, so it uses SAP's Secure Network Communications with Kerberos or X.509 certificates. SAP's help pages say this needs SAP Single Sign-On, a separately licensed product, or SAP's Secure Login Service.

4. A team lead says a sign-in ticket should go straight to a password reset. What is the better first step?
   - A. Read which check failed: most such errors aren't passwords
   - B. Reset the password, since the identity provider holds the same password
   - C. Give the user a local SAP password as a permanent workaround
   - D. Ask SAP support to reset the identity tenant

   Answer: A. With single sign-on, the application never sees the password, so resets rarely help. Reading which check failed points at the owner of the fix; a permanent local password bypasses the company's sign-in rules.

5. Which question should a leader ask before approving a new kiosk that signs technicians in with certificates?
   - A. Whether the kiosk can run SAP GUI and a browser at once
   - B. Whether the certificates can be shared between kiosks
   - C. Whether the vendor's certificates can skip expiry
   - D. Who renews each certificate, and when it expires

   Answer: D. Certificates expire by design, so every one needs an owner and a renewal date. Sharing or non-expiring certificates weaken exactly the control the kiosk is meant to provide.

6. Why should a test system's sign-in settings be checked after it is copied from production?
   - A. Test systems can't use single sign-on at all
   - B. It may still carry production's name, so sign-ins break
   - C. Production certificates are invalid in test systems by law
   - D. The copy deletes every user in the test system

   Answer: B. A service provider checks that a proof was meant for it by name. If the test system's entry carries production's name, sign-ins break, and the identity setup for test and production stops being separate.

## Deep layer

### Mental model

Treat every sign-in as **a sealed letter of introduction** carried by the browser or the PC. The identity provider writes it; the service provider reads it and asks six questions before it lets anyone in:

1. **Who wrote it?** The issuer must be one I trust.
2. **Is the seal genuine?** The signature must check against a certificate or key I hold for that issuer.
3. **Is it for me?** The audience (and, in SAML, the recipient address) must be mine.
4. **Is it fresh?** Now, by my clock, must fall inside its validity window, allowing a little skew.
5. **Is it the answer to my question?** It must match a request I sent (SAML `InResponseTo`, OpenID Connect `nonce`), and must not have been used before.
6. **Who is it about?** The name in it must match exactly one of my users.

SAML, OpenID Connect, Kerberos and certificates differ in format and transport. They don't differ in these questions. Reading a failed login is finding which question got the answer "no", and the owner of that answer.

### How it works

#### SAML 2.0 in the browser

```mermaid
sequenceDiagram
  participant B as Browser
  participant S as S4P (service provider)
  participant I as calder-ias (identity provider)
  participant E as calder-entra
  B->>S: open launchpad
  S-->>B: redirect with AuthnRequest (ID Q...)
  B->>I: AuthnRequest
  I->>E: employee: delegate (OIDC)
  E-->>I: signed ID token
  I-->>B: form with signed SAML Response
  B->>S: POST Response to the ACS URL
  S->>S: six checks, map NameID to user
  S-->>B: session cookie
```

The service provider sends an authentication request through the browser. The identity provider authenticates the person (here by handing over to Calder's Microsoft Entra ID) and returns a **Response** containing an **Assertion**. The browser posts it to the service provider's **assertion consumer service (ACS)** URL.

The OASIS SAML 2.0 profiles define what the service provider must verify for the browser single sign-on profile (section 4.1.4): the signature, a bearer `SubjectConfirmationData` whose `Recipient` is the ACS URL, a `NotOnOrAfter` that hasn't passed (allowing for clock skew), an `InResponseTo` matching the request it sent, and an `AudienceRestriction` naming the service provider; it must also reject an assertion ID it has already accepted ([OASIS SAML 2.0 profiles](https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf)). The **NameID** names the person, with a *format* (unspecified, e-mail and others) that tells the service provider how to read it.

On AS ABAP, transaction `SAML2` enables the service provider: **Enable SAML 2.0 Support** creates the *local provider*, with key pairs for signing and encryption kept as SSF applications, and two ICF services under `/sap/public/bc/sec/` must be activated ([SAP Help](https://help.sap.com/saphelp_em92/helpdata/en/4a/b4c93185376d61e10000000a42189c/content.htm)). Trusted identity providers are added from their metadata, and NameID formats are configured on the **Identity Federation** tab ([SAP Gateway example, SAP Help](https://help.sap.com/doc/saphelp_nw75/7.5.5/en-US/2b/82215150e92414e10000000a44176d/content.htm)). On the identity tenant's side, each application has its own SAML settings: by default assertions are signed, with SHA-256 for applications created after 28 June 2021, and the tenant can hold up to two signing certificates per application for the service provider's own signed requests ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-signing-certificates-and-certificate-options-9a8eade.md)).

**Certificate rotation** is where SAML outages come from. The tenant's own signing certificate can be regenerated with the same key or replaced with a new key, with validity from one month to ten years ([Tenant SAML 2.0 Configurations](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/tenant-saml-2-0-configurations-e81a19b.md)). Because every application trusts the current certificate, SAP lets an administrator choose the signing certificate per application, so applications can move to the new one one at a time; the per-application metadata download carries the chosen certificate. For tenants created before 10 September 2024, SAML and OpenID Connect shared one signing certificate until one of them is changed.

#### OpenID Connect

```mermaid
sequenceDiagram
  participant B as Browser
  participant A as calder-ai-prod app
  participant I as calder-ias
  B->>A: open app
  A-->>B: redirect: client_id, nonce
  B->>I: authorize request
  I-->>B: redirect with authorization code
  B->>A: code
  A->>I: exchange code (client credentials)
  I-->>A: ID token (JWT) + access token
  A->>A: check iss, aud, signature, exp, nonce
```

OpenID Connect adds an identity layer to OAuth 2.0. In the authorization code flow, the application gets a short-lived code through the browser and exchanges it directly with the identity provider for an **ID token**, a JSON Web Token (JWT) that must be signed. Section 3.1.3.7 of OpenID Connect Core lists the client's checks: the issuer (`iss`) must match exactly, the audience (`aud`) must contain the client's own client ID, the signature must validate, the current time must be before `exp`, `iat` can be checked for reasonableness, and the `nonce` must match the one the client sent ([OpenID Connect Core 1.0](https://openid.net/specs/openid-connect-core-1_0.html)).

On SAP BTP, a subaccount's trust to a Cloud Identity Services tenant uses OpenID Connect; the tenant then holds an application representing the subaccount, and an existing SAML trust to the same tenant must be migrated rather than doubled ([SAP BTP](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/establish-trust-and-federation-between-sap-authorization-and-trust-management-service-a-161f8f0.md)). The [secrets, API authentication and OAuth topic](https://erpfde.com/topics/secrets-api-authentication-and-oauth/) covers the OAuth side: access tokens, scopes and client credentials.

> **Note** A JWT is three base64url-encoded parts separated by dots: header, payload (the claims) and signature. Anyone can decode the first two; only the signature proves who issued it. Never paste a production token into a public decoding website: it is a live credential until it expires.

#### Kerberos: SPNEGO in the browser, SNC for SAP GUI

```mermaid
flowchart LR
  PC[Windows PC<br/>signed in to CALDER.INTERNAL] -->|1 ticket request| KDC[Active Directory<br/>key distribution center]
  KDC -->|2 service ticket| PC
  PC -->|3a browser: SPNEGO<br/>Negotiate header| W[ABAP or identity tenant]
  PC -->|3b SAP GUI: SNC| G[S4P application server]
  W -->|4 decrypt with keytab,<br/>map principal to user| W
  G -->|4 map SNC name to user| G
```

When the person signs in to Windows, the domain's key distribution center (Active Directory) issues tickets. A service presents a **service principal name**; the PC asks the KDC for a ticket for that name and hands it over. The service proves it is the right one by decrypting the ticket with a key from its **keytab**.

- **In the browser**, the server answers the first request with `401` and `WWW-Authenticate: Negotiate`, and the browser replies with the ticket (SPNEGO). SAP's identity tenant supports this for users on the corporate network; its documentation lists the supported key types (RC4 and two AES types) and requires each user to have a logon name ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-kerberos-authentication-b030165.md)). On AS ABAP, SAP's help describes installing the Secure Login Library, setting the profile parameters `spnego/enable` and `spnego/krbspnego`, loading the keytab in transaction `SPNEGO`, and mapping each Kerberos principal to a user in `SU01` ([SAP Help](https://help.sap.com/saphelp_uiaddon20/helpdata/en/87/d573d0413949c2aead2f50dd48e636/content.htm)); this requires SAP Single Sign-On 2.0 or higher, with additional licences ([SAP Help](https://help.sap.com/doc/saphelp_em92/9.2/en-US/c7/b12d71977e4b0682e327b4ecf81e9b/content.htm)).
- **In SAP GUI**, SNC carries the sign-in. SAP Single Sign-On's Secure Login supports Kerberos and X.509, separately or together, for SAP Logon, SAP Business Client and others ([SAP Help](https://help.sap.com/saphelp_em92/helpdata/en/7c/82ea543d864dacb24f371f6655dccd/content.htm)). The user's SNC name in `SU01` links the Kerberos identity to the SAP user.

Kerberos is strict about time: MIT's administration guide gives a default maximum clock skew of 300 seconds, to stop old tickets being reused ([MIT Kerberos](https://web.mit.edu/kerberos/www/krb5-1.4/krb5-1.4.1/doc/krb5-admin/Clock-Skew.html)). A PC whose clock drifted six minutes silently loses single sign-on.

#### X.509 client certificates

The client presents a certificate during the TLS handshake; the server checks it was issued by a certificate authority it trusts and is within its validity dates, then maps it to a user. On AS ABAP, transaction `CERTRULE` defines rules that take part of the certificate's subject or subject alternative name, for a given issuer, and match it to a user ID or alias. Once profile parameter `login/certificate_mapping_rulebased` is on, the rules replace manual entries in table `USREXTID`, and `CERTRULE_MIG` migrates those first ([SAP Help](https://help.sap.com/saphelp_em92/helpdata/en/c8/30fd902dc8473b9e59db1576cc784b/content.htm)). SAP's page on creating rules adds that the first matching rule applies, and if it matches but finds no user, logon fails without trying later rules ([SAP Help](https://help.sap.com/saphelp_em92/helpdata/en/7c/6d4b04370e40319ad790b554aa9a0b/content.htm)). The identity tenant can also accept certificates and, as of December 2026, can be set per application to validate them itself or pass the user on to the corporate provider ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-certificate-authentication-method-e25de8a.md)).

#### The six questions across the four protocols

| Question | SAML 2.0 | OpenID Connect | Kerberos | X.509 |
| --- | --- | --- | --- | --- |
| Who wrote it? | `Issuer` | `iss` | Realm of the principal | Certificate issuer |
| Seal genuine? | XML signature, IdP certificate | JWT signature, IdP key | Ticket decrypts with the keytab | Chain to a trusted CA |
| For me? | `Audience`, `Recipient` | `aud` | Service principal name | Accepted at this server |
| Fresh? | `NotBefore`/`NotOnOrAfter` | `iat`/`exp` | Authenticator time vs skew | `notBefore`/`notAfter` |
| Answer to my question? | `InResponseTo`, used IDs | `nonce` | Replay cache | TLS handshake |
| Who is it about? | `NameID` and its format | `sub` or a chosen claim | Principal, SNC name | Subject or alternative name |

#### Where to read a failure

- **The browser.** A SAML tracer extension shows the assertion as it passed; SAP's troubleshooting pages point to KBA 2461862 for collecting one ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Monitoring-and-Reporting/authentication-84f28fb.md)). For OpenID Connect, the token is in the application's own log or the identity tenant's.
- **The identity tenant.** **Monitoring & Reporting > Troubleshooting Logs** shows up to 1,000 entries, searched in windows of up to 60 minutes, going back 14 days ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Monitoring-and-Reporting/view-troubleshooting-logs-6e7543f.md)). With severity INFO it also logs the payload of OpenID Connect tokens it issues or receives, without `iat`, `exp` and `jti` ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Monitoring-and-Reporting/logging-openid-connect-oidc-tokens-b6c42b5.md)).
- **The error text.** SAP's troubleshooting pages quote messages that name the failed question directly, such as *Service Provider does not match specified audience in the SAML2Assertion*, *Signature validation of SAML2Assertion failed* and *SAML2Assertion does not specify Subject NameID* ([SAP](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Monitoring-and-Reporting/corporate-identity-providers-16ab7db.md)).
- **The ABAP system.** Its own security logs and traces record why it refused the assertion or ticket; the Basis team reads them there.

### Build it yourself: Calder's failed-login inbox

You will triage ten sign-in tickets from Calder's Tuesday, each with the captured message (a SAML response, an ID token, a Kerberos event or a certificate), check each against the six questions, and name the cause and the owner of the fix.

```mermaid
flowchart LR
  T[trust.json<br/>what each app accepts] --> C[checks:<br/>six questions]
  M[cases.json +<br/>SAML responses] --> C
  C --> R[triage: one verdict<br/>per ticket]
  C --> X[explain: every check<br/>for one ticket]
```

**Before you start:** complete [Set up your computer for this course](https://erpfde.com/topics/set-up-your-computer/) and [Set up for Unit 27](https://erpfde.com/topics/set-up-for-unit-27/). The [Cloud Identity Services topic](https://erpfde.com/topics/sap-cloud-identity-services/) set up Calder's tenants; this lab reads what they send.

> **Note** New words. **XML** is a tagged text format; SAML responses are XML. **JSON** is a text format for structured data. **base64url** is a way of writing binary data as plain letters; JWTs use it. A **verdict** here is the first check that failed, which names the cause.

> **Note** The lab is a model, not SAP. Element and claim names (`Issuer`, `Audience`, `NotOnOrAfter`, `InResponseTo`, `iss`, `aud`, `exp`, `nonce`) are the standards'. The signatures are stand-ins: the lab seals SAML responses and tokens with HMAC keys derived from a name, where real tenants sign with RSA private keys and an XML or JWT signature. Host names, entity IDs, client IDs, the five-minute assertion lifetime, the 120-second skew, the SNC name format and the fix owners are course labels. All people and companies are fictional.

#### What you need

- Your course folder `orchestrate-course` with its `.venv`.
- About 40 minutes. Free; built-in Python modules only, nothing to install, no network.

#### Step 1: Open your course folder and turn on the virtual environment

1. Open VS Code, choose **File > Open Folder**, and open `orchestrate-course`.
2. Open a terminal: **Terminal > New Terminal**.
3. If the prompt doesn't start with `(.venv)`, turn it on:

   - **Windows (PowerShell):**

     ```powershell
     .venv\Scripts\Activate.ps1
     ```

   - **macOS / Linux:**

     ```bash
     source .venv/bin/activate
     ```

4. The `unit27` folder exists from the unit setup. If it doesn't, create it with `mkdir unit27`.

Run every command from the course folder. On macOS or Linux, if `python` isn't found, use `python3`.

#### Step 2: Create the lab script

In VS Code, create `unit27/sso_lab.py`, paste the code below and save.

```python
"""Calder's failed-login lab: read SAML 2.0, OpenID Connect, Kerberos and X.509 sign-ins.

A local model, not SAP. Trust settings, cases L01-L10, user names, host names,
lab keys and fix owners are course labels; people and companies are fictional.
SAML signatures and JWT keys are HMAC stand-ins (real tenants sign with RSA keys).
Built-in modules only, no randomness.

  python unit27/sso_lab.py --init
  python unit27/sso_lab.py triage
  python unit27/sso_lab.py explain L02
  python unit27/sso_lab.py decode <a JWT>
  python unit27/sso_lab.py resend L01 L11 2026-12-01T13:44:30Z
  python unit27/sso_lab.py --selftest
"""
import base64
import hashlib
import hmac
import json
import shutil
import sys
import tempfile
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta
from pathlib import Path

HERE = Path(__file__).resolve().parent
DATA = HERE / "sso"
NS = {"saml": "urn:oasis:names:tc:SAML:2.0:assertion",
      "samlp": "urn:oasis:names:tc:SAML:2.0:protocol",
      "ds": "http://www.w3.org/2000/09/xmldsig#"}
NAMEID = "urn:oasis:names:tc:SAML:1.1:nameid-format:"


def lab_key(name):
    """Stand-in for a private key: a secret derived from the certificate or issuer name."""
    return hashlib.sha256(("calder-lab:" + name).encode()).digest()


def ts(text):
    return datetime.fromisoformat(text.replace("Z", "+00:00"))


def iso(moment):
    return moment.strftime("%Y-%m-%dT%H:%M:%SZ")


# ---------- trust settings: what each service provider accepts ----------

def trust():
    return {
        "lab_date": "2026-12-01",
        "identity_providers": {
            "calder-ias": {"entity_id": "https://calder-ias.accounts.example",
                           "issuer": "https://calder-ias.accounts.example",
                           "signing_certificates": {"ias-sign-2024": "2027-03-31",
                                                    "ias-sign-2026b": "2029-11-30"},
                           "default_certificate": "ias-sign-2026b",
                           "note": ("ias-sign-2026b created on 2026-11-30; S4P's application in calder-ias "
                                    "switched to it at 15:00 on 2026-12-01")},
            "calder-ias-test": {"entity_id": "https://calder-ias-test.accounts.example",
                                "issuer": "https://calder-ias-test.accounts.example",
                                "signing_certificates": {"ias-test-sign-2025": "2028-06-30"},
                                "default_certificate": "ias-test-sign-2025"},
        },
        "service_providers": {
            "S4P": {"protocol": "SAML 2.0", "entity_id": "S4PCLNT100",
                    "acs": "https://s4p.calder.internal/sap/saml2/sp/acs/100",
                    "trusted_idp": "calder-ias", "trusted_certificates": ["ias-sign-2024"],
                    "nameid_format": "unspecified", "maps_to": "user ID",
                    "skew_seconds": 120,
                    "server_clock_offset_seconds": {"s4p-app1": 0, "s4p-app2": 420}},
            "S4Q": {"protocol": "SAML 2.0", "entity_id": "S4QCLNT100",
                    "acs": "https://s4q.calder.internal/sap/saml2/sp/acs/100",
                    "trusted_idp": "calder-ias-test", "trusted_certificates": ["ias-test-sign-2025"],
                    "nameid_format": "unspecified", "maps_to": "user ID",
                    "skew_seconds": 120, "server_clock_offset_seconds": {"s4q-app1": 0}},
            "calder-ai-prod": {"protocol": "OpenID Connect", "client_id": "ai-prod-orderexc",
                               "trusted_issuer": "calder-ias", "skew_seconds": 120,
                               "maps_to": "user_uuid"},
            "dist-portal": {"protocol": "OpenID Connect", "client_id": "dist-portal-web",
                            "trusted_issuer": "calder-ias", "skew_seconds": 120,
                            "maps_to": "email"},
            "S4P-GUI": {"protocol": "Kerberos (SNC)", "realm": "CALDER.INTERNAL",
                        "service_principal": "SAP/s4p-app1.calder.internal@CALDER.INTERNAL",
                        "skew_seconds": 300, "maps_to": "SNC name"},
            "S4P-CERT": {"protocol": "X.509 client certificate",
                         "trusted_issuers": ["CN=Calder Device CA, O=Calder Pumpworks, C=US"],
                         "rule": "subject CN -> user ID", "maps_to": "user ID"},
        },
        "s4p_users": {
            "00100211": {"role": "buyer"}, "00100241": {"role": "AP accountant"},
            "00100247": {"role": "receiving clerk"}, "00100265": {"role": "customer service clerk"},
            "00100266": {"role": "inside sales rep"}, "00100153": {"role": "maintenance planner",
                                                                   "snc_name": "p:00100153@CALDER.INTERNAL"},
            "00100117": {"role": "maintenance technician", "snc_name": ""},
            "00100196": {"role": "test technician"},
        },
        "s4q_users": ["00100266"],
        "directory": {  # what calder-ias knows; user_uuid is the global user ID (course values)
            "00100304": {"user_uuid": "b7c1e2a0-0304-4c11-9a10-000100304000",
                         "email": "credit.analyst@calder-pumpworks.example"},
            "hallam-orders": {"user_uuid": "d2f0a9b1-1002-4e2b-8c55-000010000002",
                              "email": "orders@hallam-fluid.example"},
        },
        "fix_owners": {
            "SIGNATURE": "SAP Basis: import the IdP's new signing certificate into the SP's trusted provider",
            "AUDIENCE": "Owner of the app's IdP entry: the audience must be this SP's own name or client ID",
            "RECIPIENT": "Identity administrator: the ACS URL in the IdP entry",
            "ISSUER": "App team: the app trusts one issuer; the token came from another",
            "CLOCK": "Whoever runs that machine's time sync (server: SAP Basis; PC: desktop support)",
            "NAMEID": "Identity administrator: the subject name identifier sent to the app",
            "MAPPING": "Security administrator: the user record that should match the sign-in",
            "CERT_EXPIRED": "PKI owner: issue a new certificate before the old one runs out",
            "INRESPONSETO": "SAP Basis: the SP has no request with that ID (stale tab or unsolicited)",
        },
    }


# ---------- building the captured messages ----------

def saml_signature(fields, cert):
    msg = "|".join(fields).encode()
    return hmac.new(lab_key(cert), msg, hashlib.sha256).hexdigest()


def saml_response(c):
    """A SAML Response as a SAML tracer would show it, with a stand-in signature."""
    issue = ts(c["issued"])
    not_after = iso(issue + timedelta(minutes=5))
    fields = [c["issuer"], c["assertion_id"], c["nameid"], c["nameid_format"], c["audience"],
              c["recipient"], iso(issue), not_after, c["in_response_to"]]
    sig = saml_signature(fields, c["signed_with"])
    return f"""<samlp:Response xmlns:samlp="{NS['samlp']}" xmlns:saml="{NS['saml']}" xmlns:ds="{NS['ds']}"
    ID="R{c['assertion_id'][1:]}" InResponseTo="{c['in_response_to']}" IssueInstant="{iso(issue)}"
    Destination="{c['recipient']}">
  <saml:Issuer>{c['issuer']}</saml:Issuer>
  <samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
  <saml:Assertion ID="{c['assertion_id']}" IssueInstant="{iso(issue)}" Version="2.0">
    <saml:Issuer>{c['issuer']}</saml:Issuer>
    <ds:Signature><ds:KeyInfo><ds:KeyName>{c['signed_with']}</ds:KeyName></ds:KeyInfo>
      <ds:SignatureValue>{sig}</ds:SignatureValue></ds:Signature>
    <saml:Subject>
      <saml:NameID Format="{NAMEID}{c['nameid_format']}">{c['nameid']}</saml:NameID>
      <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <saml:SubjectConfirmationData Recipient="{c['recipient']}" NotOnOrAfter="{not_after}"
            InResponseTo="{c['in_response_to']}"/>
      </saml:SubjectConfirmation>
    </saml:Subject>
    <saml:Conditions NotBefore="{iso(issue - timedelta(seconds=30))}" NotOnOrAfter="{not_after}">
      <saml:AudienceRestriction><saml:Audience>{c['audience']}</saml:Audience></saml:AudienceRestriction>
    </saml:Conditions>
    <saml:AuthnStatement AuthnInstant="{iso(issue)}" SessionIndex="S-{c['assertion_id'][1:]}"/>
  </saml:Assertion>
</samlp:Response>
"""


def b64url(raw):
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def jwt(claims, issuer_name, kid):
    head = b64url(json.dumps({"alg": "HS256", "typ": "JWT", "kid": kid}).encode())
    body = b64url(json.dumps(claims).encode())
    sig = hmac.new(lab_key(issuer_name), f"{head}.{body}".encode(), hashlib.sha256).digest()
    return f"{head}.{body}.{b64url(sig)}"


def cases():
    ias, test = "https://calder-ias.accounts.example", "https://calder-ias-test.accounts.example"
    s4p_acs, s4q_acs = ("https://s4p.calder.internal/sap/saml2/sp/acs/100",
                        "https://s4q.calder.internal/sap/saml2/sp/acs/100")
    saml = [
        ("L01", "00100211", "S4P", "s4p-app1", "2026-12-01T13:42:08Z", "2026-12-01T13:42:10Z",
         ias, "ias-sign-2024", "00100211", "unspecified", "S4PCLNT100", s4p_acs,
         "Buyer opens the S4P launchpad (works: the control case)"),
        ("L02", "00100241", "S4P", "s4p-app1", "2026-12-01T15:02:31Z", "2026-12-01T15:02:33Z",
         ias, "ias-sign-2026b", "00100241", "unspecified", "S4PCLNT100", s4p_acs,
         "AP accountant: 'SAML error' page from about 15:00"),
        ("L03", "00100266", "S4Q", "s4q-app1", "2026-12-01T14:02:12Z", "2026-12-01T14:02:14Z",
         test, "ias-test-sign-2025", "00100266", "unspecified", "S4PCLNT100", s4q_acs,
         "Inside sales rep can't reach the test system for UAT"),
        ("L04", "00100247", "S4P", "s4p-app2", "2026-12-01T14:09:58Z", "2026-12-01T14:10:01Z",
         ias, "ias-sign-2024", "00100247", "unspecified", "S4PCLNT100", s4p_acs,
         "Receiving clerk: fails about half the time, works after a refresh"),
        ("L05", "00100265", "S4P", "s4p-app1", "2026-12-01T14:21:40Z", "2026-12-01T14:21:42Z",
         ias, "ias-sign-2024", "cs.clerk@calder-pumpworks.example", "emailAddress", "S4PCLNT100",
         s4p_acs, "Customer service clerk: 'user does not exist' since Friday"),
    ]
    out = []
    for (cid, user, sp, server, issued, received, issuer, cert, nameid, fmt, aud, rcpt, ticket) in saml:
        c = {"case": cid, "user": user, "target": sp, "protocol": "SAML 2.0", "server": server,
             "issued": issued, "received": received, "issuer": issuer, "signed_with": cert,
             "nameid": nameid, "nameid_format": fmt, "audience": aud, "recipient": rcpt,
             "assertion_id": "A" + hashlib.sha256(cid.encode()).hexdigest()[:20],
             "in_response_to": "Q" + hashlib.sha256((cid + "req").encode()).hexdigest()[:20],
             "ticket": ticket}
        c["message_file"] = f"{cid}_saml_response.xml"
        c["sp_requests"] = [c["in_response_to"]]  # the SP's own log of requests it sent
        out.append(c)
    d = trust()["directory"]
    oidc = [
        ("L06", "00100304", "calder-ai-prod", "2026-12-01T14:30:05Z", "2026-12-01T14:30:06Z",
         "calder-ias", ias, "dist-portal-web", d["00100304"]["user_uuid"], d["00100304"]["email"],
         "n-0601", "Credit analyst: order-exceptions app shows 'invalid token'"),
        ("L07", "hallam-orders", "dist-portal", "2026-12-01T14:36:20Z", "2026-12-01T14:36:21Z",
         "calder-ias-test", test, "dist-portal-web", d["hallam-orders"]["user_uuid"],
         d["hallam-orders"]["email"], "n-0701", "Hallam's order desk: portal loops back to sign-in"),
    ]
    for (cid, user, sp, issued, received, iname, iss, aud, uuid, email, nonce, ticket) in oidc:
        t0 = ts(issued)
        claims = {"iss": iss, "sub": uuid, "aud": aud, "user_uuid": uuid, "email": email,
                  "iat": int(t0.timestamp()), "exp": int((t0 + timedelta(minutes=60)).timestamp()),
                  "nonce": nonce}
        out.append({"case": cid, "user": user, "target": sp, "protocol": "OpenID Connect",
                    "issued": issued, "received": received, "expected_nonce": nonce,
                    "id_token": jwt(claims, iname, iname + "-k1"), "ticket": ticket})
    out += [
        {"case": "L08", "user": "00100153", "target": "S4P-GUI", "protocol": "Kerberos (SNC)",
         "client": "RKPC-0153", "principal": "00100153@CALDER.INTERNAL",
         "service_principal": "SAP/s4p-app1.calder.internal@CALDER.INTERNAL",
         "authenticator_time": "2026-12-01T14:30:55Z", "received": "2026-12-01T14:40:00Z",
         "ticket": "Planner: SAP GUI asks for a password on the new PC"},
        {"case": "L09", "user": "00100117", "target": "S4P-GUI", "protocol": "Kerberos (SNC)",
         "client": "RKPC-0117", "principal": "00100117@CALDER.INTERNAL",
         "service_principal": "SAP/s4p-app1.calder.internal@CALDER.INTERNAL",
         "authenticator_time": "2026-12-01T14:48:02Z", "received": "2026-12-01T14:48:03Z",
         "ticket": "Maintenance technician: first day with SAP GUI, no single sign-on"},
        {"case": "L10", "user": "00100196", "target": "S4P-CERT", "protocol": "X.509 client certificate",
         "client": "RKSF-0012", "subject": "CN=00100196, OU=Test bench, O=Calder Pumpworks, C=US",
         "issuer": "CN=Calder Device CA, O=Calder Pumpworks, C=US",
         "not_before": "2025-11-28T00:00:00Z", "not_after": "2026-11-28T23:59:59Z",
         "received": "2026-12-01T14:55:12Z",
         "ticket": "Test bench kiosk: readings app refuses the technician since the weekend"},
    ]
    return out


# ---------- the checks a service provider makes ----------

def check_saml(c, t):
    sp = t["service_providers"][c["target"]]
    idp = t["identity_providers"][sp["trusted_idp"]]
    text = (DATA / c["message_file"]).read_text(encoding="utf-8")
    root = ET.fromstring(text)
    a = root.find("saml:Assertion", NS)
    issuer = a.find("saml:Issuer", NS).text
    keyname = a.find("ds:Signature/ds:KeyInfo/ds:KeyName", NS).text
    sigval = a.find("ds:Signature/ds:SignatureValue", NS).text
    nid = a.find("saml:Subject/saml:NameID", NS)
    scd = a.find("saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData", NS)
    cond = a.find("saml:Conditions", NS)
    aud = cond.find("saml:AudienceRestriction/saml:Audience", NS).text
    fmt = nid.get("Format").replace(NAMEID, "")
    fields = [issuer, a.get("ID"), nid.text, fmt, aud, scd.get("Recipient"), a.get("IssueInstant"),
              scd.get("NotOnOrAfter"), scd.get("InResponseTo")]
    offset = sp["server_clock_offset_seconds"][c["server"]]
    now = ts(c["received"]) + timedelta(seconds=offset)
    skew = timedelta(seconds=sp["skew_seconds"])
    good_sig = any(hmac.compare_digest(saml_signature(fields, cert), sigval)
                   for cert in sp["trusted_certificates"])
    users = t["s4p_users"] if c["target"] == "S4P" else {u: {} for u in t["s4q_users"]}
    return [
        ("ISSUER", issuer == idp["entity_id"], f"Issuer {issuer}; {c['target']} trusts {idp['entity_id']}"),
        ("SIGNATURE", good_sig, f"signed with {keyname}; {c['target']} trusts "
                                f"{', '.join(sp['trusted_certificates'])}"),
        ("RECIPIENT", scd.get("Recipient") == sp["acs"], f"Recipient {scd.get('Recipient')}"),
        ("AUDIENCE", aud == sp["entity_id"], f"Audience {aud}; {c['target']} is {sp['entity_id']}"),
        ("CLOCK", ts(cond.get("NotBefore")) - skew <= now <= ts(scd.get("NotOnOrAfter")) + skew,
         f"valid {cond.get('NotBefore')[11:]} to {scd.get('NotOnOrAfter')[11:]}; {c['server']} "
         f"clock reads {iso(now)[11:]} (offset {offset:+d} s, skew allowed {sp['skew_seconds']} s)"),
        ("INRESPONSETO", scd.get("InResponseTo") in c["sp_requests"],
         f"InResponseTo {scd.get('InResponseTo')}"),
        ("NAMEID", fmt == sp["nameid_format"], f"NameID format {fmt}; {c['target']} expects "
                                               f"{sp['nameid_format']} mapped to {sp['maps_to']}"),
        ("MAPPING", nid.text in users, f"NameID {nid.text} -> "
                                       f"{'user ' + nid.text if nid.text in users else 'no such user'}"),
    ]


def decode_jwt(token):
    head, body, _ = token.split(".")
    pad = lambda s: s + "=" * (-len(s) % 4)
    return (json.loads(base64.urlsafe_b64decode(pad(head))),
            json.loads(base64.urlsafe_b64decode(pad(body))))


def check_oidc(c, t):
    sp = t["service_providers"][c["target"]]
    idp_name = sp["trusted_issuer"]
    idp = t["identity_providers"][idp_name]
    head, claims = decode_jwt(c["id_token"])
    h, b, s = c["id_token"].split(".")
    want = b64url(hmac.new(lab_key(idp_name), f"{h}.{b}".encode(), hashlib.sha256).digest())
    now = ts(c["received"])
    skew = sp["skew_seconds"]
    known = {v[sp["maps_to"]] for v in t["directory"].values()}
    return [
        ("ISSUER", claims["iss"] == idp["issuer"], f"iss {claims['iss']}; app trusts {idp['issuer']}"),
        ("AUDIENCE", claims["aud"] == sp["client_id"], f"aud {claims['aud']}; app's client ID is {sp['client_id']}"),
        ("SIGNATURE", hmac.compare_digest(s, want), f"kid {head['kid']}, checked with {idp_name}'s key"),
        ("CLOCK", claims["iat"] - skew <= now.timestamp() <= claims["exp"] + skew,
         f"iat {iso(datetime.fromtimestamp(claims['iat'], now.tzinfo))[11:]}, "
         f"exp {iso(datetime.fromtimestamp(claims['exp'], now.tzinfo))[11:]}, received {c['received'][11:]}"),
        ("NONCE", claims.get("nonce") == c["expected_nonce"], f"nonce {claims.get('nonce')}"),
        ("MAPPING", claims.get(sp["maps_to"]) in known, f"{sp['maps_to']} {claims.get(sp['maps_to'])}"),
    ]


def check_kerberos(c, t):
    sp = t["service_providers"][c["target"]]
    skew = abs((ts(c["received"]) - ts(c["authenticator_time"])).total_seconds())
    snc = "p:" + c["principal"]
    mapped = [u for u, v in t["s4p_users"].items() if v.get("snc_name") == snc]
    return [
        ("ISSUER", c["principal"].endswith("@" + sp["realm"]), f"principal {c['principal']}, realm {sp['realm']}"),
        ("AUDIENCE", c["service_principal"] == sp["service_principal"], f"ticket for {c['service_principal']}"),
        ("CLOCK", skew <= sp["skew_seconds"], f"{c['client']} clock {int(skew)} s away from the server "
                                              f"(allowed {sp['skew_seconds']} s)"),
        ("MAPPING", bool(mapped), f"SNC name {snc} -> {('user ' + mapped[0]) if mapped else 'no user'}"),
    ]


def check_x509(c, t):
    sp = t["service_providers"][c["target"]]
    now = ts(c["received"])
    cn = c["subject"].split(",")[0].replace("CN=", "").strip()
    return [
        ("ISSUER", c["issuer"] in sp["trusted_issuers"], f"issuer {c['issuer']}"),
        ("CERT_EXPIRED", ts(c["not_before"]) <= now <= ts(c["not_after"]),
         f"valid {c['not_before'][:10]} to {c['not_after'][:10]}; presented {c['received'][:10]}"),
        ("MAPPING", cn in t["s4p_users"], f"rule {sp['rule']}: CN {cn} -> "
                                          f"{'user ' + cn if cn in t['s4p_users'] else 'no user'}"),
    ]


CHECKERS = {"SAML 2.0": check_saml, "OpenID Connect": check_oidc,
            "Kerberos (SNC)": check_kerberos, "X.509 client certificate": check_x509}


def verdict(lines):
    first = next((code for code, ok, _ in lines if not ok), None)
    return first or "OK"


# ---------- files and commands ----------

def load():
    for name in ("trust.json", "cases.json"):
        if not (DATA / name).exists():
            sys.exit(f"{DATA / name} is missing; run: python unit27/sso_lab.py --init")
    try:
        return (json.loads((DATA / "trust.json").read_text(encoding="utf-8")),
                json.loads((DATA / "cases.json").read_text(encoding="utf-8")))
    except json.JSONDecodeError as err:
        sys.exit(f"Cannot read a JSON file in {DATA}: {err}")


def init():
    if DATA.exists():
        sys.exit(f"{DATA} already exists; delete the folder first to start over")
    DATA.mkdir(parents=True)
    all_cases = cases()
    for c in all_cases:
        if c["protocol"] == "SAML 2.0":
            (DATA / c["message_file"]).write_text(saml_response(c), encoding="utf-8")
    (DATA / "trust.json").write_text(json.dumps(trust(), indent=2), encoding="utf-8")
    (DATA / "cases.json").write_text(json.dumps(all_cases, indent=2), encoding="utf-8")
    print(f"Wrote {DATA}: trust.json, cases.json ({len(all_cases)} cases), "
          f"{sum(c['protocol'] == 'SAML 2.0' for c in all_cases)} SAML responses")


def triage():
    t, cs = load()
    counts = {}
    print(f"{'Case':5} {'User':14} {'Protocol':25} {'Target':15} Verdict")
    for c in sorted(cs, key=lambda x: x["case"]):
        v = verdict(CHECKERS[c["protocol"]](c, t))
        counts[v] = counts.get(v, 0) + 1
        print(f"{c['case']:5} {c['user']:14} {c['protocol']:25} {c['target']:15} {v}")
    bad = {k: n for k, n in counts.items() if k != "OK"}
    print(f"\n{counts.get('OK', 0)} OK, {sum(bad.values())} failed: "
          + ", ".join(f"{k} {n}" for k, n in sorted(bad.items(), key=lambda kv: (-kv[1], kv[0]))))
    print("Synthetic data: course cases, not a real tenant's logs.")
    return counts


def explain(case_id):
    t, cs = load()
    c = next((x for x in cs if x["case"] == case_id.upper()), None)
    if c is None:
        sys.exit(f"No case {case_id}; use L01 to L{len(cs):02d}")
    lines = CHECKERS[c["protocol"]](c, t)
    print(f"{c['case']}  {c['user']} -> {c['target']} ({c['protocol']}), received {c['received']}")
    print(f"Ticket: {c['ticket']}")
    for n, (code, ok, detail) in enumerate(lines, 1):
        print(f"  {n} {code:13} {'OK  ' if ok else 'FAIL'} {detail}")
    v = verdict(lines)
    print(f"Verdict: {v}")
    if v != "OK":
        print(f"Fix owner: {t['fix_owners'].get(v, 'not listed in trust.json')}")
    return v


def resend(src, new_id, when):
    """Post a captured message again, as an attacker or a stale browser tab would."""
    t, cs = load()
    c = next(x for x in cs if x["case"] == src.upper())
    copy = dict(c, case=new_id.upper(), received=when, ticket=f"Copy of {c['case']} posted again")
    cs.append(copy)
    (DATA / "cases.json").write_text(json.dumps(cs, indent=2), encoding="utf-8")
    print(f"Added {copy['case']}: {c['case']}'s message received again at {when}")


def selftest():
    global DATA
    keep = DATA
    with tempfile.TemporaryDirectory() as tmp:
        DATA = Path(tmp) / "sso"
        try:
            init()
            t, cs = load()
            want = {"L01": "OK", "L02": "SIGNATURE", "L03": "AUDIENCE", "L04": "CLOCK",
                    "L05": "NAMEID", "L06": "AUDIENCE", "L07": "ISSUER", "L08": "CLOCK",
                    "L09": "MAPPING", "L10": "CERT_EXPIRED"}
            got = {c["case"]: verdict(CHECKERS[c["protocol"]](c, t)) for c in cs}
            assert got == want, got
            head, claims = decode_jwt(next(c for c in cs if c["case"] == "L06")["id_token"])
            assert head["alg"] == "HS256" and claims["aud"] == "dist-portal-web"
        finally:
            DATA = keep
    print("Self-test passed: 10 cases give their planted verdicts (synthetic data)")


def main(argv):
    if not argv or argv[0] in ("-h", "--help"):
        print(__doc__)
    elif argv[0] == "--init":
        init()
    elif argv[0] == "--selftest":
        selftest()
    elif argv[0] == "triage":
        triage()
    elif argv[0] == "explain" and len(argv) == 2:
        explain(argv[1])
    elif argv[0] == "decode" and len(argv) == 2:
        head, claims = decode_jwt(argv[1])
        print("Header: ", json.dumps(head))
        print("Payload:", json.dumps(claims, indent=2))
        print("Decoded only: the signature was NOT checked.")
    elif argv[0] == "resend" and len(argv) == 4:
        resend(*argv[1:])
    else:
        sys.exit("Unknown command. Run: python unit27/sso_lab.py --help")


if __name__ == "__main__":
    main(sys.argv[1:])
```

#### Step 3: Write the inbox

1. Run:

   ```bash
   python unit27/sso_lab.py --init
   ```

2. You should see:

   ```text
   Wrote .../orchestrate-course/unit27/sso: trust.json, cases.json (10 cases), 5 SAML responses
   ```

3. Open `unit27/sso/L01_saml_response.xml` in VS Code. It is shaped like what a SAML tracer shows for the buyer's sign-in to `S4P`. Find the six answers in it:

   ```text
   <saml:Issuer>https://calder-ias.accounts.example</saml:Issuer>              who wrote it
   <ds:KeyName>ias-sign-2024</ds:KeyName>                                     which seal
   <saml:Audience>S4PCLNT100</saml:Audience>                                  for whom
   Recipient="https://s4p.calder.internal/sap/saml2/sp/acs/100"               delivered where
   NotBefore="2026-12-01T13:41:38Z" NotOnOrAfter="2026-12-01T13:47:08Z"       fresh until
   InResponseTo="Qd796fdd5a85734078ea3"                                       answers request
   <saml:NameID Format="...:unspecified">00100211</saml:NameID>               about whom
   ```

4. Open `unit27/sso/trust.json`. Under `service_providers`, `S4P` lists what it accepts: issuer, the one certificate it trusts (`ias-sign-2024`), its own name `S4PCLNT100`, its ACS URL, the NameID format it expects, and the clock offset of each application server.

#### Step 4: Triage the inbox

1. Run:

   ```bash
   python unit27/sso_lab.py triage
   ```

2. You should see:

   ```text
   Case  User           Protocol                  Target          Verdict
   L01   00100211       SAML 2.0                  S4P             OK
   L02   00100241       SAML 2.0                  S4P             SIGNATURE
   L03   00100266       SAML 2.0                  S4Q             AUDIENCE
   L04   00100247       SAML 2.0                  S4P             CLOCK
   L05   00100265       SAML 2.0                  S4P             NAMEID
   L06   00100304       OpenID Connect            calder-ai-prod  AUDIENCE
   L07   hallam-orders  OpenID Connect            dist-portal     ISSUER
   L08   00100153       Kerberos (SNC)            S4P-GUI         CLOCK
   L09   00100117       Kerberos (SNC)            S4P-GUI         MAPPING
   L10   00100196       X.509 client certificate  S4P-CERT        CERT_EXPIRED

   1 OK, 9 failed: AUDIENCE 2, CLOCK 2, CERT_EXPIRED 1, ISSUER 1, MAPPING 1, NAMEID 1, SIGNATURE 1
   Synthetic data: course cases, not a real tenant's logs.
   ```

> **Note** These counts come from synthetic course data. They show the method of reading failures, not how often each cause occurs in a real landscape.

Nine failures, six causes, four protocols: the same questions decide every one.

#### Step 5: Explain the certificate switch (L02)

1. Run:

   ```bash
   python unit27/sso_lab.py explain L02
   ```

2. You should see:

   ```text
   L02  00100241 -> S4P (SAML 2.0), received 2026-12-01T15:02:33Z
   Ticket: AP accountant: 'SAML error' page from about 15:00
     1 ISSUER        OK   Issuer https://calder-ias.accounts.example; S4P trusts https://calder-ias.accounts.example
     2 SIGNATURE     FAIL signed with ias-sign-2026b; S4P trusts ias-sign-2024
     3 RECIPIENT     OK   Recipient https://s4p.calder.internal/sap/saml2/sp/acs/100
     4 AUDIENCE      OK   Audience S4PCLNT100; S4P is S4PCLNT100
     5 CLOCK         OK   valid 15:02:01Z to 15:07:31Z; s4p-app1 clock reads 15:02:33Z (offset +0 s, skew allowed 120 s)
     6 INRESPONSETO  OK   InResponseTo Q1dcfd5368889c3964b4d
     7 NAMEID        OK   NameID format unspecified; S4P expects unspecified mapped to user ID
     8 MAPPING       OK   NameID 00100241 -> user 00100241
   Verdict: SIGNATURE
   Fix owner: SAP Basis: import the IdP's new signing certificate into the SP's trusted provider
   ```

3. Read it. `trust.json` notes that `ias-sign-2026b` was created on 30 November and `S4P`'s application in `calder-ias` was switched to it at 15:00. The buyer's sign-in at 13:42 (L01) worked because it was still sealed with the old certificate. The right order: Basis adds the new certificate to `S4P`'s trusted provider first, then the identity team switches the application.

#### Step 6: Explain the clock and the name (L04, L05)

1. Run `python unit27/sso_lab.py explain L04`. Check 5 fails:

   ```text
     5 CLOCK         FAIL valid 14:09:28Z to 14:14:58Z; s4p-app2 clock reads 14:17:01Z (offset +420 s, skew allowed 120 s)
   ```

   `S4P` has two application servers. `s4p-app2` runs seven minutes fast, so the assertion looks expired there. That is why the clerk's ticket says "fails about half the time": it depends on which server the load balancer picks.

2. Run `python unit27/sso_lab.py explain L05`. Checks 7 and 8 fail:

   ```text
     7 NAMEID        FAIL NameID format emailAddress; S4P expects unspecified mapped to user ID
     8 MAPPING       FAIL NameID cs.clerk@calder-pumpworks.example -> no such user
   Verdict: NAMEID
   ```

   The identity tenant now sends the clerk's e-mail as the name. `S4P` looks for a user called `cs.clerk@calder-pumpworks.example` and finds none. The second failure follows from the first: the verdict is always the first failed check.

#### Step 7: Read an ID token (L06, L07)

1. Run `python unit27/sso_lab.py explain L06`. The audience is wrong:

   ```text
     2 AUDIENCE      FAIL aud dist-portal-web; app's client ID is ai-prod-orderexc
   ```

   The order-exceptions app asked for a token with the distributor portal's client ID, likely a copied configuration. The token is genuine, but it isn't for this app.

2. Open `unit27/sso/cases.json`, find `"case": "L06"`, and copy the long `id_token` value (without the quotes).
3. Decode it, pasting your copy in place of `<token>`:

   ```bash
   python unit27/sso_lab.py decode <token>
   ```

   ```text
   Header:  {"alg": "HS256", "typ": "JWT", "kid": "calder-ias-k1"}
   Payload: {
     "iss": "https://calder-ias.accounts.example",
     "sub": "b7c1e2a0-0304-4c11-9a10-000100304000",
     "aud": "dist-portal-web",
     ...
     "nonce": "n-0601"
   }
   Decoded only: the signature was NOT checked.
   ```

   Decoding shows the claims; it proves nothing. That's why the lab's `explain` checks the signature separately.

4. Run `python unit27/sso_lab.py explain L07`. Checks 1 and 3 fail: the distributor portal in production received a token from `calder-ias-test`. The issuer is wrong, and the signature fails because the app checks with production's key. The portal's production deployment points at the test tenant.

#### Step 8: Kerberos and the certificate (L08 to L10)

1. Run `python unit27/sso_lab.py explain L08`: the planner's new PC is 545 seconds off, above Kerberos's 300. Desktop support fixes the time source; nobody touches SAP.
2. Run `python unit27/sso_lab.py explain L09`: the technician's ticket is fine, but no `S4P` user carries the SNC name `p:00100117@CALDER.INTERNAL`. The security administrator fills the SNC field of the user in `SU01`.
3. Run `python unit27/sso_lab.py explain L10`: the kiosk certificate ran out on 28 November. The rule would map `CN=00100196` to the right user, but the certificate is checked first.

#### Step 9: Run the self-test and save your work

1. Run:

   ```bash
   python unit27/sso_lab.py --selftest
   ```

   ```text
   Wrote .../sso: trust.json, cases.json (10 cases), 5 SAML responses
   Self-test passed: 10 cases give their planted verdicts (synthetic data)
   ```

   The self-test works in a temporary folder, so your `unit27/sso` stays as it is.

2. Save your work with Git:

   ```bash
   git add unit27/sso_lab.py unit27/sso
   git commit -m "Unit 27: single sign-on failed-login lab"
   ```

To start over, delete the folder `unit27/sso` and run `--init` again. The output never varies: there is no randomness.

#### How the code works

| Part | What it does |
| --- | --- |
| `trust()` | What each service provider accepts: issuer, trusted certificates or keys, its own name or client ID, ACS URL, NameID format, clock offsets, users |
| `cases()` | The ten tickets with their captured messages and planted faults |
| `saml_response()` | Writes a SAML Response shaped like a tracer capture, sealed with the stand-in signature |
| `jwt()` and `decode_jwt()` | Build and read a JSON Web Token: base64url header, payload and HMAC signature |
| `check_saml()` | Parses the XML and answers the six questions in the order a service provider would |
| `check_oidc()` | Applies the OpenID Connect Core checks: `iss`, `aud`, signature, `iat`/`exp`, `nonce`, then the user |
| `check_kerberos()`, `check_x509()` | Realm, service principal, clock skew and SNC name; issuer, validity dates and the CN rule |
| `verdict()` | Returns the first failed check: later failures usually follow from it |
| `triage()`, `explain()` | One line per ticket, or every check for one ticket with the fix owner |
| `resend()` | Posts a captured message again, as a stale tab or an attacker would (used in the exercise) |

#### If something goes wrong

| What you see | What it means | What to do |
| --- | --- | --- |
| `python: command not found` or `'python' is not recognized` | Python isn't on your PATH, or `.venv` is off | Turn on `.venv` (Step 1); on macOS/Linux try `python3` |
| `trust.json is missing` | `--init` hasn't run | Run `python unit27/sso_lab.py --init` |
| `already exists; delete the folder first` | `--init` won't overwrite your work | Delete `unit27/sso` only if you want the sample back |
| `Cannot read a JSON file` | A hand edit broke the JSON | Undo the edit, or delete the folder and run `--init` |
| `No case L12` | That case doesn't exist yet | Use `L01` to `L10` (or `L11` after the exercise) |
| `binascii.Error` or `ValueError` when decoding | The token was cut short when copied | Copy the whole value between the quotes, with both dots |
| `ParseError` | A SAML file was edited and is no longer valid XML | Delete the folder and run `--init` |
| A corporate proxy or missing library message | Not this lab: it needs no network or packages | Follow the course setup topic's notes for other steps |

### The SAP way

In real systems, the lab's settings live here (names as in SAP's documentation on 1 December 2026):

| Lab | Where it lives | Notes |
| --- | --- | --- |
| `S4P.trusted_idp`, `trusted_certificates` | AS ABAP transaction `SAML2`: trusted identity provider, from its metadata | Update when the tenant's certificate changes |
| `S4P.entity_id`, `acs` | `SAML2`: local provider name and endpoints | Must differ between test and production |
| `nameid_format`, `maps_to` | `SAML2`: the trusted provider's **Identity Federation** tab; the tenant's subject name identifier for the application | Both sides must agree |
| `calder-ias.signing_certificates` | Identity tenant: **Applications** > application > **Trust** > **SAML 2.0 Configuration**; tenant SAML 2.0 configuration | Signing certificate selectable per application |
| `calder-ai-prod.client_id`, `trusted_issuer` | BTP subaccount trust to the tenant (OpenID Connect) and the app's service binding | One tenant per subaccount on this route |
| `S4P-GUI` | SNC with SAP Single Sign-On or Secure Login Service; SNC name in `SU01` | Licensed separately |
| Kerberos in the browser | `SPNEGO` transaction and parameters `spnego/enable`, `spnego/krbspnego`; or the tenant's Kerberos setting | Keytab and service principal from the directory team |
| `S4P-CERT.rule` | `CERTRULE` with `login/certificate_mapping_rulebased` | First matching rule decides |
| `skew_seconds`, clock offsets | The servers' and PCs' time synchronisation | Not an SAP setting at all |

> **Note** **Sketch, needs systems.** Every row needs administrator access to a real ABAP system, identity tenant, BTP subaccount or Active Directory domain. The [Unit 27 setup](https://erpfde.com/topics/set-up-for-unit-27/) has no such system. Calder's systems are fictional; the lab is the free path.

### Build vs. SAP

| Need | Use SAP's mechanism | Build something |
| --- | --- | --- |
| Browser sign-in to S/4HANA | SAML 2.0 from the identity tenant | Never a custom login page in front of S/4HANA |
| Sign-in to your own BTP app | OpenID Connect through the subaccount's trust and the app's binding | Only the token checks your framework doesn't do for you, and use a maintained library for those |
| SAP GUI without passwords | SNC with SAP Single Sign-On or Secure Login Service | Nothing: no supported home-made route |
| Kiosks and machines | X.509 with `CERTRULE` rules | The certificate inventory and renewal alerts, if your PKI tool has none |
| Reading failures | Tenant troubleshooting logs, tracers, ABAP traces | A small triage script like the lab's for the help desk's first look, read-only |

### Architecture view

**Where it sits.** The identity tenant is the hub for browser sign-in; Active Directory is the hub for Kerberos; the company's certificate authority is the hub for certificates:

```mermaid
flowchart LR
  E[calder-entra] -- OIDC --- T[calder-ias]
  T -- SAML 2.0 --> S4P[S4P launchpad]
  T -- OIDC --> BTP[calder-ai-prod,<br/>dist-portal]
  TT[calder-ias-test] -- SAML 2.0 --> S4Q[S4Q]
  AD[Active Directory<br/>CALDER.INTERNAL] -- Kerberos via SNC --> GUI[S4P for SAP GUI]
  CA[Calder Device CA] -- X.509 --> K[S4P from kiosks]
```

**Non-functional requirements that decide the design:**

| Requirement | Calder's target | What breaks if missed |
| --- | --- | --- |
| Certificate continuity | New signing certificate trusted by every application 14 days before any switch; kiosk certificates renewed 30 days before expiry | Mass lockout, as in L02; idle kiosks, as in L10 |
| Time | Every server and PC within 60 seconds of the domain's time source | Intermittent SAML failures (L04) and lost SAP GUI single sign-on (L08) |
| Stable user name | Applications receive the login name or global user ID, never a changeable e-mail | "User does not exist" after a mailbox rename (L05) |
| Separation | Test systems and test tenants have their own names, certificates and keys | Test using production identity, or failing on it (L03, L07) |
| Diagnosis | Help desk can name the failed check within 15 minutes | Password resets that fix nothing |

The targets are course values for Calder.

**Integration and identity.** Employees authenticate once at `calder-entra`; `calder-ias` turns that into a SAML assertion for `S4P` and ID tokens for BTP apps, with the login name or global user ID as the subject, as the [Cloud Identity Services topic](https://erpfde.com/topics/sap-cloud-identity-services/) designed. SAP GUI and RFC use SNC and never touch the tenant. When a BTP app or agent calls S/4HANA for the user, [principal propagation](https://erpfde.com/topics/principal-propagation/) carries the identity onward.

**The decision to record.** In the form from [the design-doc topic](https://erpfde.com/topics/writing-a-solution-design-doc/):

- **Context:** SAP GUI users at Rockford type passwords; Calder must choose how to give them single sign-on.
- **Options:** (a) keep passwords, enforce complexity; (b) SAP Single Sign-On with Kerberos on the Rockford domain; (c) SAP Secure Login Service for SAP GUI, a cloud service issuing short-lived certificates after a sign-in at Calder's identity provider.
- **Decision:** (b) for Rockford today, a course assumption: Calder already runs Active Directory, the PCs are domain-joined, and the licence is in the RISE order. Revisit (c) when `CP20` joins in July 2027 and Augsburg's PCs sit in another domain.
- **Consequences:** time synchronisation and SNC names in `SU01` become controls; leavers lose SAP GUI access when their Windows account is disabled, but their SAP user still needs locking for any other route.

**What a design review will ask:**

1. For each SAP application, which protocol, which identity provider and which name does it receive?
2. Show the certificate rotation runbook: who adds, who switches, in what order, and how you test before the switch.
3. How do you keep test and production trust apart, including copies made by system refresh?
4. What happens to SAP GUI and browser access on the day someone leaves?
5. How does the help desk read a failure, and which logs can it see?

### Production concerns

- **Security.** Keep assertion and token lifetimes short and the skew allowance small. Require signed assertions (the tenant's default) and keep SHA-256 or stronger. Remove trust to identity providers nobody uses. Kerberos in the browser gives no transport security on its own; SAP's help says to use TLS with it.
- **SAP authorizations.** Single sign-on decides *who*; roles decide *what*. A name mapping error can sign someone in as the wrong user, so test mappings with real joiners, movers and renamed mailboxes. The [authorization concept topic](https://erpfde.com/topics/sap-authorization-concept-in-depth/) covers the rest.
- **Evaluation.** Keep a sign-in test set per protocol: one working case and each known failure, rerun after every certificate, clock or mapping change. The lab's ten cases are a template.
- **Operations.** Track every certificate (tenant signing, ABAP SAML keys, kiosk and SNC certificates) with an owner and expiry date. Monitor time drift on application servers. Keep the tenant's 14-day troubleshooting window in mind: export logs for anything you may need later.
- **Cost.** SAP Single Sign-On and Secure Login Service are licensed; confirm what your contract includes before promising SAP GUI single sign-on.
- **Clean core.** All of this is configuration and standard protocols; nothing here needs custom code in S/4HANA.

### Where AI fits

**An agent is one more relying party, and one more sender.** When a person uses an AI app on BTP, the app receives the person's ID token like any other; when the agent then calls S/4HANA, the person's identity must travel with the call so SAP's authorization checks still apply. That onward step is [principal propagation](https://erpfde.com/topics/principal-propagation/). The [agent permissions topic](https://erpfde.com/topics/agent-permissions-and-sap-authorizations/) explains why a technical user in its place is the wrong answer.

**AI can help read failures.** Pasting a captured assertion's fields and a troubleshooting log into an assistant that explains which check failed is a reasonable help-desk aid, as long as the assertion or token is expired or redacted first: a live token is a credential. Changing trust settings, certificates or mappings stays with the named owners, not an agent.

### Pitfalls

- **Switching the identity provider's signing certificate before every application trusts it.** Move applications one at a time.
- **Sending e-mail as the user's name** to systems that look users up by login name, or that keep the old address after a rename.
- **Copying a production system or configuration into test** and keeping production's entity ID, client ID or tenant.
- **Ignoring clocks.** SAML and Kerberos both reject proofs from the wrong time, and one drifting server makes failures look random.
- **Reading only the last error.** The first failed check is the cause; later ones usually follow from it.
- **Decoding tokens on public websites.** Use a local tool, and only on expired or test tokens.
- **Assuming SAP GUI single sign-on is free.** Check the licence first.
- **Certificates without owners.** Every expiry is a dated outage unless someone renews it.

### Exercise: catch a replayed assertion

The SAML profiles say a service provider must refuse an assertion ID it has already accepted. The lab doesn't check that yet. You will post L01's response a second time and add the check.

1. Post the buyer's response again two minutes later:

   ```bash
   python unit27/sso_lab.py resend L01 L11 2026-12-01T13:44:30Z
   python unit27/sso_lab.py triage
   ```

   The last line of the table shows `L11 ... S4P OK`: the copy still passes every check, because it is genuine and not yet expired.

2. Open `unit27/sso_lab.py`. Just above the line `CHECKERS = {`, paste this function:

   ```python
   def replay_check(c, cs):
       """A SAML assertion is good for one use: refuse an ID this SP has already accepted."""
       earlier = [x["case"] for x in cs if x["protocol"] == "SAML 2.0" and x["target"] == c["target"]
                  and x["received"] < c["received"] and x["assertion_id"] == c["assertion_id"]]
       return ("REPLAY", not earlier, f"assertion ID {c['assertion_id']} "
               + (f"already used by {earlier[0]}" if earlier else "not seen before"))
   ```

3. In `triage()`, replace the line `v = verdict(CHECKERS[c["protocol"]](c, t))` with these four lines (keep the indentation of the line you replace):

   ```python
           lines = CHECKERS[c["protocol"]](c, t)
           if c["protocol"] == "SAML 2.0":
               lines.append(replay_check(c, cs))
           v = verdict(lines)
   ```

4. In `explain()`, just below `lines = CHECKERS[c["protocol"]](c, t)`, add the same two lines, indented to match:

   ```python
       if c["protocol"] == "SAML 2.0":
           lines.append(replay_check(c, cs))
   ```

5. Open `unit27/sso/trust.json` and add an owner inside `"fix_owners"`, after the `"INRESPONSETO"` line (put a comma at the end of that line first):

   ```json
   "REPLAY": "Security team: a used assertion was posted again; find the source before anything else"
   ```

6. Run the triage and the explanation:

   ```bash
   python unit27/sso_lab.py triage
   python unit27/sso_lab.py explain L11
   ```

   ```text
   L11   00100211       SAML 2.0                  S4P             REPLAY

   1 OK, 10 failed: AUDIENCE 2, CLOCK 2, CERT_EXPIRED 1, ISSUER 1, MAPPING 1, NAMEID 1, REPLAY 1, SIGNATURE 1
   ...
     9 REPLAY        FAIL assertion ID A8e029448a5228c68cbe4 already used by L01
   Verdict: REPLAY
   ```

7. Run `python unit27/sso_lab.py --selftest` and commit.

**Done when:** `triage` shows `L01` as `OK` and `L11` as `REPLAY`, `explain L11` names the fix owner from `trust.json`, and the self-test still passes. Keep `unit27/sso/` and your triage output for your portfolio: the [principal propagation topic](https://erpfde.com/topics/principal-propagation/) follows the same user one hop further, from a BTP app to S/4HANA.

### Check yourself

1. A service provider receives a SAML response. Which of these is NOT one of the checks it must make?
   - A. The signature validates against a certificate it trusts for that issuer
   - B. The audience names this service provider
   - C. The person's password meets the company's complexity rules
   - D. `NotOnOrAfter` has not passed, allowing for clock skew

   Answer: C. The service provider never sees the password; the identity provider checked it. The SAML profiles require the signature, recipient, audience, time and `InResponseTo` checks, and refusing reused assertion IDs.

2. In L02, the AP accountant's sign-ins to S4P fail with a signature error right after 15:00, while the buyer's sign-in at 13:42 worked. What is the right fix order?
   - A. Switch every application to the new certificate at once, then import it in S4P
   - B. Import the new certificate into S4P, then switch S4P's application
   - C. Turn off assertion signing until both certificates are trusted
   - D. Ask the accountant to clear browser cookies and sign in again

   Answer: B. S4P accepts only assertions sealed with a certificate it trusts. SAP lets the signing certificate be chosen per application so each one can move after its service provider trusts the new certificate; turning off signing removes the proof altogether.

3. The receiving clerk's sign-in to S4P fails about half the time and works after a refresh. What does the lab's L04 show as the cause?
   - A. The identity tenant issues assertions that live only a few seconds
   - B. The clerk's NameID alternates between login name and e-mail
   - C. The load balancer drops the `InResponseTo` value on every other request
   - D. One of two app servers runs seven minutes fast

   Answer: D. Freshness is judged by the receiving server's clock. With two servers and one drifting, the failure depends on which server answers, which looks random until you compare clocks.

4. In `check_oidc()`, which claim tells the order-exceptions app that a genuine token was not issued for it?
   - A. `iss`
   - B. `aud`
   - C. `nonce`
   - D. `sub`

   Answer: B. OpenID Connect Core requires the audience to contain the client's own client ID. In L06 the issuer and signature are right, but `aud` carries the distributor portal's client ID, so the app must refuse it.

5. Why does `verdict()` report only the first failed check?
   - A. Later failures usually follow from the first one
   - B. Service providers stop parsing the message after one failure, so later checks are unknown
   - C. The standards forbid reporting more than one error to the user
   - D. Checks after the first are always run on stale data

   Answer: A. In L05 the wrong NameID format also leaves no user to match, and in L07 the wrong issuer explains the failed signature. Fixing the first cause usually clears the rest, which is why the help desk should start there.

6. The planner's SAP GUI asks for a password on a new PC; the Kerberos ticket is for the right service and the SNC name is mapped. What should the team check first?
   - A. The identity tenant's SAML signing certificate
   - B. The S4P user's roles in `SU01`
   - C. The PC's clock against the domain's time source
   - D. The kiosk certificate rule in `CERTRULE`

   Answer: C. Kerberos rejects authenticators outside the allowed clock skew, 300 seconds by default in MIT's guide; L08's PC is 545 seconds off. SAP GUI single sign-on doesn't use the identity tenant's SAML certificate at all.

7. Which AS ABAP setting decides which user a kiosk's X.509 certificate signs in as?
   - A. The NameID format on the `SAML2` Identity Federation tab
   - B. The profile parameter `spnego/krbspnego`
   - C. The client ID in the BTP service binding
   - D. A `CERTRULE` rule mapping part of the subject to a user ID or alias

   Answer: D. Rule-based certificate mapping takes part of the subject or alternative name for a trusted issuer and matches it to a user. SAP's help adds that the first matching rule decides, and a match with no user fails without trying others.

8. A developer wants to paste a production ID token into a public JWT website to debug a sign-in. What do you advise?
   - A. Fine: the header and payload are only base64url, so nothing is exposed
   - B. Fine, as long as the signature part is removed first
   - C. Don't: it's a live credential until expiry; decode it locally
   - D. Don't: decoding a JWT changes its signature and invalidates it

   Answer: C. Anyone holding a valid token can present it until `exp`. Decoding is harmless to the token but exposes it to the site; the lab's `decode` command does the same locally and says the signature was not checked.

## Sources

- [Describing the Standards for Authentication and Provisioning (SAP Learning, Introducing SAP Cloud Identity Services, read 2026-12-01)](https://learning.sap.com/courses/introducing-sap-cloud-identity-services/describing-the-standards-for-authentication-and-provisioning_af14db99-1815-4e30-9dde-e14d2a76815e): SAML 2.0 is what SAP and its customers use today; OpenID Connect is an identity layer on OAuth 2.0 returning an ID token (a JWT) and is the recommended protocol for integrating with Identity Authentication for SAP cloud applications; SAML no longer strategic for direct BTP to corporate IdP integration; SCIM for provisioning
- [Enabling the SAML Service Provider (AS ABAP, help.sap.com, read 2026-12-01)](https://help.sap.com/saphelp_em92/helpdata/en/4a/b4c93185376d61e10000000a42189c/content.htm): transaction SAML2, Enable SAML 2.0 Support creates a local provider; SSF applications for signing and encryption key pairs; ICF services /sap/public/bc/sec/saml2 and cdc_ext_service to activate
- [Using Kerberos Authentication on SAP NetWeaver Application Server ABAP (help.sap.com, read 2026-12-01)](https://help.sap.com/doc/saphelp_em92/9.2/en-US/c7/b12d71977e4b0682e327b4ecf81e9b/content.htm): AS ABAP supports Kerberos with SPNEGO for web clients; requires SAP Single Sign-On 2.0 or higher, which requires additional software licenses; SPNEGO gives no transport security, so use TLS
- [SNC with SAP Single Sign-On Secure Login (help.sap.com, read 2026-12-01)](https://help.sap.com/saphelp_em92/helpdata/en/7c/82ea543d864dacb24f371f6655dccd/content.htm): Secure Login gives single sign-on and encryption between SAP GUI and AS ABAP through SNC; Kerberos and X.509 separately or together; additional licenses
- [Rule-Based Certificate Mapping (AS ABAP, help.sap.com, read 2026-12-01)](https://help.sap.com/saphelp_em92/helpdata/en/c8/30fd902dc8473b9e59db1576cc784b/content.htm): transaction CERTRULE maps parts of a certificate's subject or subject alternative name for an issuer to a user ID or alias; replaces table USREXTID once profile parameter login/certificate_mapping_rulebased is on; CERTRULE_MIG migrates
- [Configure Kerberos Authentication (SAP Cloud Identity Services documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-kerberos-authentication-b030165.md): Identity Authentication supports Kerberos with SPNEGO for users on the corporate network; 401 with WWW-Authenticate: Negotiate; ticket from the KDC (e.g. Active Directory); keytab from a service user; SPN for the tenant host; RC4 and AES key types supported; users need a logon name
- [Configure Signing Certificates and Certificate Options (SAP Cloud Identity Services documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Operation-Guide/configure-signing-certificates-and-certificate-options-9a8eade.md): the identity provider certificate used for signing can be chosen per application so applications can be moved to a new certificate one by one; defaults: sign assertions on, SHA-256 for applications created after 28 June 2021
- [Corporate Identity Providers troubleshooting (SAP Cloud Identity Services documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-identity-services/blob/main/docs/Monitoring-and-Reporting/corporate-identity-providers-16ab7db.md): error texts such as 'Service Provider does not match specified audience in the SAML2Assertion', 'Signature validation of SAML2Assertion failed', 'SAML2Assertion does not specify Subject NameID', InResponseTo missing
- [Establish Trust and Federation Between SAP Authorization and Trust Management Service and SAP Cloud Identity Services (SAP BTP documentation, read 2026-12-01)](https://github.com/SAP-docs/btp-cloud-platform/blob/main/docs/50-administration-and-ops/establish-trust-and-federation-between-sap-authorization-and-trust-management-service-a-161f8f0.md): subaccount trust to a Cloud Identity Services tenant by OpenID Connect, no SAML metadata exchange; one tenant per subaccount this way; existing SAML trust to the same tenant must be migrated to OIDC
- [OpenID Connect Core 1.0 (OpenID Foundation, read 2026-12-01)](https://openid.net/specs/openid-connect-core-1_0.html): the ID token is a JWT and must be signed; section 3.1.3.7 lists the client's checks: issuer, audience, signature, expiry, issued-at, nonce
