Skip to main content

Keycloak XOAUTH2 Email: Microsoft 365 and Gmail

Keycloak can authenticate to an SMTP relay with an OAuth2 access token instead of a password. Set Authentication Type to token on the realm's Email tab and fill in five fields — token URL, scope, client id, client secret, and the username the mail is sent as. Keycloak then runs a client_credentials grant against the token URL, caches the token per realm, and presents it to the relay as SASL XOAUTH2. Microsoft 365 works. Gmail does not, and cannot, because Google does not implement the client-credentials grant with a client secret.

Two things will cost you an afternoon if nobody tells you, and nobody does:

  1. The scope in Keycloak's own documentation is not the one Microsoft requires for app-only SMTP. Keycloak's server admin guide says https://outlook.office.com/.default. Microsoft's client-credentials page for SMTP says, in its own words, "You must use https://outlook.office365.com/.default in the scope property in the body payload for the access token request."
  2. Keycloak caches the access token for up to its expiry plus 30 seconds, per realm, and nothing in the console or the docs says so. That is why a secret you just rotated keeps working, and why a token that just expired gets sent anyway.
Tested against

Keycloak 26.8.2 (quay.io/keycloak/keycloak:26.8.2, start-dev) on 2026-11-30, against an SMTP relay instrumented to log the whole SASL exchange and decode the token. Every log line, error string and timestamp quoted below is copied from that run. Behaviour that cannot be observed from outside — the cache key, the 30-second grace, the fallback lifetime — was read from TokenAuthEmailAuthenticator.java on the release/26.8 branch and then confirmed by measurement.

The Microsoft tenant steps are from Microsoft's own documentation, linked inline. They were not run against a live tenant here; the Keycloak half of the exchange was.

This page assumes you already have working SMTP. If you do not, start with configure SMTP so Keycloak can send email and come back — everything about hosts, ports, encryption and the From address is the same, and only the Authentication section changes.

What the five token fields actually do​

Keycloak's token fetch is one HTTP POST with four form parameters. There is no variation, no negotiation, and no extension point:

Console labelRealm config keyWhat Keycloak does with it
UsernameuserGoes in the SASL string as user=<this>. Not the From address.
Auth Token URLauthTokenUrlPOSTed to, as application/x-www-form-urlencoded
Auth Token ScopeauthTokenScopeSent as scope=
Auth Token ClientIdauthTokenClientIdSent as client_id=
Auth Token Client SecretauthTokenClientSecretSent as client_secret=. May be a ${vault.…} reference.

Plus a fixed grant_type=client_credentials. That is the whole request.

Read the consequences off that list before you plan anything:

  • Client authentication is client_secret_post only. No HTTP Basic, no private_key_jwt, no client_assertion, no mTLS. A token endpoint that insists on Basic authentication for the client cannot be used.
  • There is no resource parameter, so an authorization server that wants the audience named that way is out.
  • The username field is load-bearing and separate from From. With Microsoft 365 it has to be the mailbox the service principal was granted access to.

The secret comes back as "**********" from the Admin REST API, the same as a password — masked on read, stored in full.

What Keycloak puts on the wire​

This is the part no documentation shows, and it is worth seeing once because every failure below is a deviation from it. Captured at the relay:

S: 220 relay.example.test ESMTP
C: EHLO 114ead0e5c1c
S: 250-relay.example.test
S: 250-8BITMIME
S: 250-AUTH XOAUTH2 PLAIN LOGIN
S: 250 SMTPUTF8
C: AUTH XOAUTH2 dXNlcj1rZXljbG9ha0BleGFtcGxlLnRlc3QBYXV0aD1CZWFyZXIgZXlKaGJHY2lPaUpT…
S: 235 2.7.0 Authentication successful
C: MAIL FROM:<keycloak@example.test>

Base64-decoded, that one command line is:

user=keycloak@example.test^Aauth=Bearer eyJhbGciOiJSUzI1NiIs…^A^A

^A is 0x01. The format is SASL XOAUTH2, and three details matter:

  • Keycloak sends the blob as an initial response on the AUTH line, not after a 334 challenge. Both forms are legal; a relay that only implements the two-step form will not work.
  • user= is the realm's Username field. If it does not match a mailbox your token is authorized for, the relay rejects a perfectly valid token.
  • Keycloak offers XOAUTH2 and nothing else. With authType=token it sets mail.smtp.auth.mechanisms=XOAUTH2, so there is no fallback to PLAIN even when the relay advertises it. That is the right behaviour — a silent downgrade to a password you did not configure would be worse — but it means "the relay does not speak XOAUTH2" surfaces as an authentication failure rather than as a capability failure.

Turning on smtpServer.debug=true prints the exchange into the server log, with the credential redacted by Jakarta Mail rather than by Keycloak:

DEBUG SMTP: Found extension "AUTH", arg "XOAUTH2 PLAIN LOGIN"
DEBUG SMTP: Attempt to authenticate using mechanisms: XOAUTH2
DEBUG SMTP: Using mechanism XOAUTH2
DEBUG SMTP: AUTH XOAUTH2 command trace suppressed
DEBUG SMTP: AUTH XOAUTH2 succeeded

The token is not written to the log even at debug level. Leave debug off in production anyway — it logs every recipient address.

Configure it for Microsoft 365​

The Keycloak half is five fields. The tenant half is six steps, and five of them are invisible from Keycloak — if any one is missed, Keycloak gets a valid access token and the relay still answers 535.

1. Register the application and give it the SMTP permission​

In Microsoft Entra, register an application, then under API permissions → APIs my organization uses → Office 365 Exchange Online → Application permissions, add SMTP.SendAsApp. Grant tenant admin consent. The delegated SMTP.Send scope is the wrong one here: it belongs to the authorization-code flow, and Keycloak has no user to authorize.

2. Register the service principal in Exchange Online​

Entra consent is not enough. Exchange keeps its own service principal directory, and the app has to be in it:

Install-Module -Name ExchangeOnlineManagement
Connect-ExchangeOnline -Organization <tenantId>

New-ServicePrincipal -AppId <APPLICATION_ID> -ObjectId <OBJECT_ID>

-ObjectId is the object id from the Enterprise Applications blade, not the one on the App Registrations overview page. Microsoft calls this out explicitly, because the two look identical and the wrong one produces an authentication failure with no hint as to why.

3. Grant the mailbox​

$sp = Get-ServicePrincipal -Identity "<display name you gave it>"
Add-MailboxPermission -Identity "keycloak@contoso.com" -User $sp.Identity -AccessRights FullAccess

If you want Keycloak's From address to differ from the mailbox, you also need Add-RecipientPermission for SendAs. Simpler: make the Username field and the From address the same mailbox, and set a friendly From display name instead.

4. Make sure SMTP AUTH is on for that mailbox​

SMTP AUTH is disabled by default for tenants created after January 2020, at the tenant level and per mailbox. Check Get-CASMailbox before blaming Keycloak.

5. Point Keycloak at it​

kcadm update realms/prod \
-s 'smtpServer.host=smtp.office365.com' \
-s 'smtpServer.port=587' \
-s 'smtpServer.starttls=true' \
-s 'smtpServer.auth=true' \
-s 'smtpServer.authType=token' \
-s 'smtpServer.from=keycloak@contoso.com' \
-s 'smtpServer.user=keycloak@contoso.com' \
-s 'smtpServer.authTokenUrl=https://login.microsoftonline.com/<TenantID>/oauth2/v2.0/token' \
-s 'smtpServer.authTokenScope=https://outlook.office365.com/.default' \
-s 'smtpServer.authTokenClientId=<ApplicationId>' \
-s 'smtpServer.authTokenClientSecret=${vault.m365-smtp-secret}'

Port 587 with STARTTLS, not 465: Microsoft states that 465 does not support the TLS versions it requires for client submission. Keycloak sets mail.smtp.starttls.required=true whenever you enable STARTTLS, so a relay that stops advertising STARTTLS fails closed rather than sending in the clear.

6. About that scope​

Keycloak's server admin guide gives https://outlook.office.com/.default. Microsoft's client-credentials instructions for SMTP say https://outlook.office365.com/.default, and use the same value for the admin-consent URL. Keycloak's section is marked as community-contributed and "provided as-is" by the core team, so where the two disagree, Microsoft's is the one to follow. If the first attempt fails, this is the first field to change.

Why you are doing this now​

Microsoft's updated deprecation timeline, published 2026-01-27:

WhenWhat happens to SMTP AUTH basic authentication
Now to December 2026Unchanged
End of December 2026Disabled by default for existing tenants; an admin can re-enable it
New tenants after December 2026Unavailable by default
Second half of 2027Microsoft announces the final removal date

Password authentication to smtp.office365.com has a year left at the outside, and a re-enable toggle in between. XOAUTH2 is the exit.

Why Gmail does not work​

Keycloak's documentation says Google "is not yet supported … because Google does not allow client-secrets for the Client Credentials Grant." That is accurate, and it is not a gap someone will close with configuration.

Google's SMTP scope is https://mail.google.com/ and Gmail does accept SASL XOAUTH2 — the problem is upstream of SMTP. A Google service account gets a token by signing a JWT and posting it with grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer and an assertion parameter. Keycloak posts grant_type=client_credentials with a client_secret, as shown above, and has no code path that builds or signs an assertion. The two do not meet.

So for Google Workspace, pick one of these instead, and know what each costs:

OptionHow it authenticatesWhat you give up
App password on a Workspace mailboxPassword, via authType=basicA long-lived shared secret; requires 2-Step Verification on the account, and an admin can disable app passwords org-wide
Google Workspace SMTP relay (smtp-relay.gmail.com)IP allowlist, optionally plus credentialsStatic egress IPs from every Keycloak node, which rules out most autoscaled deployments
A transactional relay in front of GmailWhatever that relay supportsAnother vendor, another bill, better deliverability reporting
A custom EmailSenderProvider SPIWhatever you implement, including the Gmail APIYou own and upgrade Java code in Keycloak's send path

The honest default is the second or third. An app password works today, but it is the credential class every provider is moving away from, and you will be back here.

Amazon SES is the other common relay with no XOAUTH2 at all — its SMTP endpoint requires a password, and its SMTP credentials are not your IAM key pair.

The token cache nobody documents​

Keycloak keeps one access token per realm in memory. The cache entry is keyed on token URL, scope, client id, and a hash of the client secret, and it is reused as long as all four still match and the token has not been expired for more than 30 seconds.

Measured, with a 300-second token issued at 07:30:06 and therefore expiring at 07:35:06 — the relay logs the jti of every token it is shown:

Timejti presented
07:30:06e11be6ab… (first fetch)
07:33:03e11be6ab…
07:35:06e11be6ab… — expired
07:35:32e11be6ab… — expired 26s ago, sent anyway
07:35:3769b0b764… (refetched)

Four consequences, in the order they will bite you:

  • Keycloak will present an expired token. The grace is applied after expiry, not before it: expiration_at.plusSeconds(30).isAfter(now). A relay that checks exp strictly answers 535 for those last thirty seconds. It recovers — see the retry below — but the failure is real and it is periodic.
  • Rotating the client secret takes effect immediately. The secret hash is part of the cache key, so the next send after you save the new value fetches a new token. The same goes for changing the scope, the client id or the token URL. Nothing to restart.
  • Rotating the secret at the provider does not. Entra does not tell Keycloak, so the cached token stays valid until it expires on its own. Overlap the two secrets in Entra for at least one token lifetime before you remove the old one.
  • A token response with no expires_in is assumed to last 60 seconds, and Keycloak logs Got no expires_in from response for SMTP auth in realm …. Every send then costs a token fetch. If you see that warning in a busy realm, that is your throughput ceiling.

The cache lives in a single Keycloak process. In a cluster, each node holds its own — so a three-node cluster makes three times the token requests, and a per-client rate limit at the authorization server has to be sized for the cluster, not for the realm.

When it breaks, read the right line​

Every one of these produces the same thing in the console: a 500 and {"errorMessage":"Failed to send email"}. The cause is only in the server log, and the top-level message is often not the useful one. All four reproduced on 26.8.2:

Top line in the server logWhat is actually wrong
EmailException: Failed to gather valid token for SMTP, with Caused by: java.net.ConnectExceptionKeycloak cannot reach the token URL at all. Egress rules, proxy, DNS. SMTP was never attempted.
EmailException: No access token found in token-response for SMTPThe authorization server refused. The WARN line immediately above prints its entire response body.
EmailException: Retry after AuthenticationFailed-Exception for SMTP failed. with Caused by: jakarta.mail.AuthenticationFailedException: No authentication mechanisms supported by both server and clientThe relay does not advertise XOAUTH2. Nothing to do with your token.
EmailException: Retry after AuthenticationFailed-Exception for SMTP failed. with Caused by: jakarta.mail.AuthenticationFailedException: 334 <base64> and OAUTH2 asked for moreThe relay rejected the token. The reason is inside that base64 string.

That second row is the one to internalise. Keycloak logs the token endpoint's answer verbatim, which means the provider's own error code is sitting in your log:

WARN [org.keycloak.email.TokenAuthEmailAuthenticator] Got no access_token from response
for SMTP auth in realm mail, response was
{"error":"invalid_scope","error_description":"Invalid scopes: https://relay.example.test/.default"}
WARN [org.keycloak.email.TokenAuthEmailAuthenticator] Got no access_token from response
for SMTP auth in realm mail, response was
{"error":"unauthorized_client","error_description":"Invalid client or Invalid client credentials"}

Against Entra, the same line carries the AADSTS code, which is the thing you search for.

Decode the 334 challenge​

When a relay rejects a token the way RFC 7628 specifies, it sends a base64 JSON document explaining why. Jakarta Mail does not decode it and does not send the empty continuation line the RFC asks for — it gives up with OAUTH2 asked for more and puts the raw challenge in the exception message. So the real answer is in your log, encoded:

echo 'eyJzdGF0dXMiOiAiNDAxIiwgInNjaGVtZXMiOiAiYmVhcmVyIiwgInNjb3BlIjogImh0dHBzOi8vcmVsYXkuZXhhbXBsZS50ZXN0Ly5kZWZhdWx0In0=' | base64 -d
{"status": "401", "schemes": "bearer", "scope": "https://relay.example.test/.default"}

scope in that reply is the scope the relay expected. Against Microsoft 365 this is how you find out you used outlook.office.com where outlook.office365.com was wanted, without guessing.

One failure, two connections​

Keycloak retries an authentication failure exactly once, and the retry is not a reconnect with the same token — it discards the cached token, fetches a brand new one, and opens a second SMTP connection. Confirmed at the relay: two connections, two different jti values, both rejected, inside the same second.

That is what makes the expired-token window self-healing. It also means a misconfiguration generates two failed authentications per attempted email at your provider, which counts toward whatever throttling or lockout Exchange Online applies. Fix a red SMTP config promptly rather than leaving it to retry.

Keep the secret out of the realm configuration​

authTokenClientSecret is masked on read, but it is stored in the realm and it travels in a realm export. Keycloak resolves it through the vault SPI, so a reference works in its place. With the file vault:

printf 'the-entra-client-secret' > /opt/keycloak/vault/prod_m365-smtp-secret

kc.sh start --vault=file --vault-dir=/opt/keycloak/vault
kcadm update realms/prod -s 'smtpServer.authTokenClientSecret=${vault.m365-smtp-secret}'

The file name is <realm>_<key>; the realm config holds only the reference. Verified end to end on 26.8.2 — the relay authenticated against a secret Keycloak read from the vault, and the realm JSON never contained it.

Verify it​

Test connection — the button, or POST /admin/realms/<realm>/testSMTPConnection with the config as the body — returns 204 when the relay accepted a message and 500 with Failed to send email for every one of the four causes above. The response body never tells you which; the server log does.

A passing test proves the token path works now. It proves nothing about five minutes from now, when the cache turns over and a fresh token is fetched with whatever the app registration looks like by then. For that, watch SEND_RESET_PASSWORD_ERROR and SEND_VERIFY_EMAIL_ERROR in the realm's events — Keycloak email not sending has the method.

Next steps​