Learn»
OpenID Connect has become the leading standard for single sign-on andidentity provision on the Internet. Its formula for success: simpleJSON-based identity tokens (JWT), delivered via OAuth 2.0 flows that fit web,browser-based and native / mobileapplications.
1. Local user authentication vs IdentityProviders
Applications often need to authenticate their users. The simplistic approach isto set up a local database for the users' accounts and credentials. Givenenough technical care this can be made to work well. However, localauthentication can be bad forbusiness:
People find account creation tedious, and rightly so. This can cause consumersites and apps to suffer abandoned shopping cards, and hence loss ofbusiness andsales.
For enterprises with a multitude of apps, the maintenance of separate userdatabases can easily turn into an administrative and security nightmare. Youmay want to put your IT resources to betteruse.
The established solution to these problems is to delegate user authenticationand provisioning to a dedicated, purpose-built service, called an IdentityProvider(IdP).
Google, Facebook and Twitter, where many people have accounts, offer such IdPservices for their users. A consumer web site can greatly streamline its useronboarding by integrating login with thoseIdPs.
In a enterprise, this would ideally be one internal IdP service, for employeesand contractors to log into the internal applications. A central login hasconsiderable benefits, such as easier administration and faster development ofnew apps. You may ask: Isn't that going to create a single point of failure?No, not when the IdP service is built forredundancy.
2. Enter OpenIDConnect
OpenID Connect,published in 2014, is not the first standard for identity provision, butdefinitely the best in terms of usability and simplicity, having learnedlessons from past efforts such asSAML andOpenID 1.0 and2.0.
What is the formula for success of OpenIDConnect?
Easy to consume identity tokens: Clients receive the user's identityencoded in a secure JSON Web Token (JWT), called an ID token. JWTs areappreciated for their elegance and portability, and for their ready supportfor a wide range of signature and encryption algorithms. All that makes JWToutstanding for the ID tokenjob.
Based on the OAuth 2.0 framework: The ID token is obtained via a standardOAuth 2.0 flow, with flows available for web as well as native / mobile apps.OAuth 2.0 also means having one protocol for authentication and authorisation(obtaining accesstokens).
Simplicity: OpenID Connect is simple enough to integrate with basic apps,but it also has the features and security options to satisfy complexrequirements of enterprises, fintechs andgovernments.
3. The IDtoken
The ID tokenresembles the concept of an identity card, in a standard JWTformat, signed by the OpenID Provider (OP). To obtain one the client needs tosend the user to their OP with an authenticationrequest.
Features of the IDtoken:
- Asserts the identity of the user, called subject in OpenID(sub).
- Specifies the issuing authority(iss).
- Is generated for a particular audience, i.e. client(aud).
- May contain a nonce(nonce).
- May specify when (auth_time) and how, in terms of strength (acr), the userwasauthenticated.
- Has an issue (iat) and expiration time(exp).
- May include additional requested details about the subject, such as name andemailaddress.
- Is digitally signed, so it can be verified by the intendedrecipient.
- May optionally be encrypted forconfidentiality.
The ID token statements, or claims, are packaged in a simple JSONobject:
{ "sub" : "alice", "iss" : "https://openid.c2id.com", "aud" : "client-12345", "nonce" : "n-0S6_WzA2Mj", "auth_time" : 1311280969, "acr" : "https://load.c2id.com/high", "iat" : 1311280970, "exp" : 1311281970}
The ID token header, claims JSON and signature are encoded into a base 64URL-safestring:
eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOWdkazcifQ.ewogImlzcyI6ICJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5NzYxMDAxIiwKICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZfV3pBMk1qIiwKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5NzAKfQ.ggW8hZ1EuVLuxNuuIJKX_V8a_OMXzR0EHR9R6jgdqrOOF4daGU96Sr_P6qJp6IcmD3HP99Obi1PRs-cwh3LO-p146waJ8IhehcwL7F09JdijmBqkvPeB2T9CJNqeGpe-gccMg4vfKjkM8FcGvnzZUN4_KSP0aAp1tOJ1zZwgjxqGByKHiOtX7TpdQyHE5lcMiKPXfEIQILVq0pc_E2DzL7emopWoaoZTF_m0_N0YzFC6g6EJbOEoRoSK5hoDalrcvRYLSrQAZZKflyuVCyixEoV9GfNQC3_osjzw2PAithfubEEBLuVVk4XUVrWOLrLl0nx7RkKU8NXNHq-rvKMzqg
You can read more about the JWT data structure and its encoding in RFC7519.
4. How to request an IDtoken
Now that we know what an ID token is, how can a client, calledRelying Party (RP) in OpenID Connect, requestone?
Authentication must take place at the identity provider, where the user'ssession or credentials will be checked. For that a trusted agent is required,and this role is usually performed by the webbrowser.
A browser popup is the preferred way for a web application to redirect the userto the IdP. Mobile apps on platforms such as Android or iOS should launch thesystem browser for that purpose. Embedded web views are not be trusted, asthere is nothing to prevent the app from snooping on the user password. Userauthentication must always occur in a trusted context that is separate from theapp (e.g. thebrowser).
Note that OpenID Connect doesn't specify how users should actually beauthenticated, this is left up to the IdP todecide.
ID tokens are requested via the OAuth 2.0 protocol, which has been atremendous success on its own. OAuth was originally devised as a simpleauthorisation mechanism for apps to obtain access tokens for web APIs or otherprotected resources. It has flows designed for all application types:traditional server-based web applications, browser (JavaScript) only apps, andnative / mobileapps.
So what are those flows, or paths, for obtaining IDtokens?
Authorisation code flow-- the most commonly used flow, intended for traditional web apps as well asnative / mobile apps. Involves an initial browser redirection to / from theOP for user authentication and consent, then a second back-channel request toretrieve the ID token. This flow offers optimal security, as tokens are notexposed to the browser and the client can also beauthenticated.
Implicit flow-- for browser (JavaScript) based apps that don't have a backend. The IDtoken is received directly with the redirection response from the OP. Noback-channel request is requiredhere.
Hybrid flow-- rarely used, allows the application front-end and back-end to receivetokens separately from one another. Essentially a combination of the code andimplicitflows.
The OpenID Connect spec provides a nicecomparisonof the three flows, reproduced here in a simplifiedform.
Flow property | Code | Implicit | Hybrid |
---|---|---|---|
Browser redirection step | ✔ | ✔ | ✔ |
Backend request step | ✔ | ✕ | ✔ |
Tokens revealed to browser | ✕ | ✔ | ✔ |
Client can be authenticated | ✔ | ✕ | ✔ |
5. Cool ID tokenuses
An ID token can be put to uses beyond basicsign-in:
Stateless sessions -- Put into a browser cookie the ID token canimplement a lightweight stateless session. This does away with the need tostore sessions on the server side (in memory or on disk), which can be aburden to manage and scale. The session is checked by validating the IDtoken. When the token reaches some predefined age past its issue timestamp(iat) the application can simply ask the OP for a new one via a silentprompt=nonerequest.
Passing identity to 3rd parties -- The ID token may be passed to otherapplication components or to backend services when knowledge of the user'sidentity is required, for example to log audittrails.
Token exchange -- The ID token may be exchanged for an access token atthe token endpoint of an OAuth 2.0 authorisation server(RFC 8693). There are real worldscenarios when an identity document is required to obtain access, for examplewhen you check in at a hotel to get your room key. Token exchange has uses indistributed and enterpriseapplications.
6. Example OpenIDauthentication
We will now go through a minimal example of how to obtain an ID token for auser from an OP, using the authorisation code flow.This is the most commonly used flow by traditional web applications. Examplesof the implicitand hybrid flowcan be found in the OpenID Connectspec.
The code flow has twosteps:
Step 1 | Step 2 | |
---|---|---|
Purpose | 1. Authenticate user 2. Receive user consent | 1. Authenticate client (optional) 2. Exchange code for token(s) |
Via | Front-channel request (browser redirection) | Back-channel request (app to web server) |
To | Authorisation endpoint | Token endpoint |
Result on success | Authorisation code (step 2 input) | ID token (+ OAuth 2.0 access token) |
Code flow: Step1
The RP initiates user authentication by redirecting the browser to theOAuth 2.0 authorisation endpointof the OpenID Provider. The OpenID authentication requestis essentially an OAuth 2.0 authorisation requestto access the user's identity, indicated by an openid
value in the scopeparameter.
Example authentication redirection to theOP:
HTTP/1.1 302 FoundLocation: https://openid.c2id.com/login? response_type=code &scope=openid &client_id=s6BhdRkqt3 &state=af0ifjsldkj &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb
The request parameters are encoded in the URIquery:
response_type Set to
code
to indicate an authorisation codeflow.scope Used to specify the scope of the requested authorisation in OAuth.The scope value
openid
signals a request for OpenID authentication and IDtoken.client_id The client identifier of the RP at the OP. This identifier isassigned when the RP is registered with the OP, via the client registrationAPI, a developer console, or some othermethod.
state Opaque value set by the RP to maintain state between request andcallback.
redirect_uri The RP callback URI for the authenticationresponse.
At the OP, the user will typically be authenticated by checking if they have avalid session (established by a browser cookie), and in the absence of that, byprompting the user to login. After that the user will typically be askedwhether they agree to sign into theRP.
The OP will then call the client redirect_uri
with an authorisation code (onsuccess) or an error code (if access was denied, or some other error occurred,such a malformed request wasdetected).
HTTP/1.1 302 FoundLocation: https://client.example.org/cb? code=SplxlOBeZQQYbYS6WxSbIA &state=af0ifjsldkj
The RP must validate the state
parameter, and use the code
to proceed tothe next step - exchanging the code for theIDtoken.
Code flow: Step2
The authorisation code is an intermediate credential, which encodes theauthorisation obtained at step 1. It istherefore opaque to the RP and only has meaning to the OP server. To retrievethe ID token the RP must submit the code to the OP, but this time with a directback-channel request. This is done for tworeasons:
- To authenticate confidential clients with the OP before revealing thetokens;
- To deliver the tokens straight to the RP, thus avoid exposing them to thebrowser.
The code-for-token exchange happens at the token endpoint oftheOP:
POST /token HTTP/1.1Host: openid.c2id.comContent-Type: application/x-www-form-urlencodedAuthorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JWgrant_type=authorization_code &code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb
The client ID and secret are passed via the Authorization
header. Apart fromHTTP basic authenticationOpenID Connect also supports authentication with aJWT, which doesn't expose the clientcredentials with the token request, has expiration, and thus provides strongersecurity.
The token request parameters areform-encoded:
grant_type Set to
authorization_code
.code The code obtained from step1.
redirect_uri Repeats the callback URI from step1.
On success the OP will return a JSON object with the ID token, an access tokenand an optional refreshtoken:
HTTP/1.1 200 OKContent-Type: application/jsonCache-Control: no-storePragma: no-cache{ "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOWdkazcifQ.ewogImlzc yI6ICJodHRwOi8vc2VydmVyLmV4YW1wbGUuY29tIiwKICJzdWIiOiAiMjQ4Mjg5 NzYxMDAxIiwKICJhdWQiOiAiczZCaGRSa3F0MyIsCiAibm9uY2UiOiAibi0wUzZ fV3pBMk1qIiwKICJleHAiOiAxMzExMjgxOTcwLAogImlhdCI6IDEzMTEyODA5Nz AKfQ.ggW8hZ1EuVLuxNuuIJKX_V8a_OMXzR0EHR9R6jgdqrOOF4daGU96Sr_P6q Jp6IcmD3HP99Obi1PRs-cwh3LO-p146waJ8IhehcwL7F09JdijmBqkvPeB2T9CJ NqeGpe-gccMg4vfKjkM8FcGvnzZUN4_KSP0aAp1tOJ1zZwgjxqGByKHiOtX7Tpd QyHE5lcMiKPXfEIQILVq0pc_E2DzL7emopWoaoZTF_m0_N0YzFC6g6EJbOEoRoS K5hoDalrcvRYLSrQAZZKflyuVCyixEoV9GfNQC3_osjzw2PAithfubEEBLuVVk4 XUVrWOLrLl0nx7RkKU8NXNHq-rvKMzqg" "access_token": "SlAV32hkKG", "token_type": "Bearer", "expires_in": 3600,}
The ID token is a JWT and must be properlyvalidatedby the RP before it can beaccepted.
Note that a bearer access token is alsoincluded. This is to ensure the token responseis compliant with the OAuth 2.0 spec. Forbasic OpenID authentication requests where only an ID token is requested thisaccess token is nominal and may be safely ignored. The access token howevercomes into play when also requesting access to user profile data at theUserInfo endpoint. More on this in the nextchapter.
7. Claims (userinfo)
OpenID Connect specifies a set of standardclaims,or user attributes. They are intended to supply the client with consented userdetails such as email, name and picture, upon request. Languagetags enablelocalisation.
Scopevalue | Associated claims |
---|---|
email, email_verified | |
phone | phone_number, phone_number_verified |
profile | name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture, website, gender, birthdate, zoneinfo, locale, updated_at |
address | address |
Clients can request claims in twoways:
- An entire claims category by its
scope
value (see the above table for thescope value to claimmappings) - Individually, with the optional claimsrequestparameter.
Example request to access the user's identity (ID token) and email, by simplysetting the scope to openidemail
:
HTTP/1.1 302 FoundLocation: https://openid.c2id.com/login? response_type=code &scope=openid%20email &client_id=s6BhdRkqt3 &state=af0ifjsldkj &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb
If you're an application developer, respect the user's privacy and keep therequested claims down to the very essential. This will increase your chances ofuser conversion and will also ensure compliance with recent privacylaws.
Note that even if a user allows an application to access their identity,they may choose to deny release of some claims. The application should be ableto handle such decisionsgracefully.
The claims format isJSON:
{ "sub" : "alice", "email" : "[emailprotected]", "email_verified" : true, "name" : "Alice Adams", "given_name" : "Alice", "family_name" : "Adams", "phone_number" : "+359 (99) 100200305", "profile" : "https://c2id.com/users/alice", "https://c2id.com/groups" : [ "audit", "admin" ]}
OpenID providers may extend the standard JSON claims schema to includeadditional attributes.Enterprises may for instance define claims such as employee role, manager, anddepartment. The names of any additional claims should be prefixed by a URL tocreate a safe namespace for them and preventcollisions.
8. OpenID Connect providerendpoints
Core endpoints | Optional endpoints |
---|---|
|
|
8.1 Authorisationendpoint
This is the OP server endpoint where the user is asked toauthenticate and grant the client access to the user'sidentity (ID token) and potentially other requested details, such as email andname (called UserInfoclaims).
This is the only standard endpoint where users interact with the OP, via a useragent, which role is typically assumed by a webbrowser.
8.2 Tokenendpoint
The token endpoint lets the client appf exchange the code received from theauthorisation endpoint for an ID token and access token. Ifthe client is confidential it will be required to authenticate at the tokenendpoint.
The token endpoint it may also accept other OAuth 2.0 granttypes to issue tokens, forexample:
8.3 UserInfoendpoint
The UserInfo endpointreturns previously consented user profile information to the client. A validaccess token is required forthat.
GET /userinfo HTTP/1.1Host: openid.c2id.comAuthorization: Bearer sa7Aebo6Ookoo0oh
The UserInfo is JSON encoded and may optionally be packaged as a JWT that issigned orencrypted.
HTTP/1.1 200 OKContent-Type: application/json{ "sub" : "alice", "email" : "[emailprotected]", "email_verified" : true, "name" : "Alice Adams", "picture" : "https://c2id.com/users/alice.jpg"}
8.4 Optionalendpoints
OpenID Connect providers can have these additionalendpoints:
WebFinger --Enables dynamic discovery of the OpenID Connect provider for a given user,based on their email address or some otherdetail.
Provider metadata --JSON document listing the OP endpoint URLs and the OpenID Connect / OAuth 2.0features it supports. Clients can use this information to configure theirrequests to theOP.
Provider JWK set -- JSON document containing the provider's public keys(typically RSA) in JSON Web Key (JWK) format. These keys are used to securethe issued ID tokens and otherartifacts.
Client registration --RESTful web API for registering client apps with the OP. Registration may beprotected (require pre-authorisation) or open(public).
Session management --Enables client apps to check if a logged in user has still an active sessionwith the OpenID Connect provider. Also to facilitatelogout.
9. Where is thespec?
The standard was produced by a working group at the OpenIDfoundation and comprises a set of documents which can beexplored athttp://openid.net/connect/.
10.FAQ
10.1 How is OpenID Connect related to OAuth2.0?
OAuth 2.0 is a framework for obtaining access tokens for protectedresources such as web APIs. OpenID Connect utilises the OAuth 2.0 semantics andflows to allow clients (relying parties) to access the user's identity, encodedin a JSON Web Token (JWT) called ID token. The access token facilitatesretrieval of consented profile details (called claims or attributes) from theUserInfo endpoint of the OpenIDprovider.
10.2 How do OpenID providers authenticateusers?
OpenID Connect leaves this entirely up to the particular IdP. Implementors mayuse any method for authenticating users, or combine two methods for strongersecurity(2FA).
- Username /password
- Hardwaretokens
- SMSconfirmation
- Biometrics
- Etc.
The IdP may set the optional acr
and amr
claims in the IDtoken to inform the client how the user has beenauthenticated.
Clients are also have control overauthentication:
The optional
prompt=login
parameter will cause the user to be(re)authenticated, even if they have a valid session (cookie) with theIdP.With IdPs that support various authentication strengths, the application mayrequest stronger authentication using the optional
acr_values
parameter.
10.3 What is a bearer accesstoken?
The access token resembles the concept of a physical token or ticket. It givesthe holder access to a specific HTTP resource or web service, which istypically limited by scope and has an expirationtime.
Bearer access tokens are easy to use - whoever has one is permitted to call theprotected resource. For that reason they must always be passed around over asecure channel (TLS / HTTPS) and storedsecurely.
OpenID Connect employs OAuth 2.0 access tokens to allow client apps toretrieve consented user information from the UserInfoendpoint.
An OpenID provider may extend the access token scope to other protectedresources and webAPIs.