Authorization Code flow
- Basic flow described in OAuth2 and OpenID Connect 1 specifications
- Supported in Keycloak from it's early days
Step A
- User accesses secured URL on application side (or click login)
- Application redirects browser to Keycloak with Authorization Request
Authorization request example
http://localhost:8080/auth/realms/example/protocol/openid-connect/auth
?client_id=js-console
&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fjs-console%2F
&state=aea3526d-ee91-4f17-b262-d794e49e16d0
&response_type=code
Step B
Keycloak authenticates user (doesn't matter how)
and optionally show grant screen
Step C
- Authorization Response - Keycloak redirects through user's browser to the application with code and state parameters
- URL of redirection was specified by redirect_uri parameter sent earlier in Authorization Request
- Must be allowed in client configuration in Keycloak admin console (Valid Redirect URIs)
Authorization response example
http://localhost:8080/js-console/
?state=aea3526d-ee91-4f17-b262-d794e49e16d0
&code=TNe8_fSjxFRQhaI78SjxbScncZ3Roy5lJQIEiLCiXBE.0a55d203-9f7f-4b52-b496-e23b1477fd0b
Step D and E
- Client application sends out-of-bound request to exchange code for token
- Browser is not involved in typical server-side applications
- Token request is POST request. It contains code and is authenticated with client credentials
- Token response contains:
- access_token
- id_token
- refresh_token
- Both client credentials and tokens are hidden from browser (and user) in server-side applications
Token request example
POST: http://localhost:8080/auth/realms/example/protocol/openid-connect/token
code=TNe8_fSjxFRQhaI78SjxbScncZ3Roy5lJQIEiLCiXBE.0a55d203-9f7f-4b52-b496-e23b1477fd0b
&grant_type=authorization_code
&client_id=js-console
&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fjs-console%2F
Response from token request
{
"access_token":"eyJhbGciOiJSUzI1...",
"expires_in":300,
"refresh_token":"eyJhbGciOiJSU...",
"refresh_expires_in":1800,
"token_type":"bearer",
"id_token":"eyJhbGc...",
"not-before-policy":0,
"session-state":"f58c76c1-85b9-4bbb-a26d-ebf56ec47334"
}