OAuth 2.0 explained (2024)

Need to protect an application with tokens? The OAuth 2.0 security frameworkis what you're looking for. It has flows for web, mobile and IoT clients,plus useful APIs for managing the token lifecycle. What started as a simpleand effective solution for granting 3rd party access to socialprofiles, has evolved to support applications in a range of domains, witheven the most stringent securityrequirements.

1. Token-based security with OAuth2.0

OAuth 2.0 explained (1)

The token has become a popular pattern for securing applications on theinternet. Developers love its conceptual simplicity, architects the ability todesign applications with nicely decoupled security roles. However, in theseeming ease of putting together token-based security lurkpitfalls.

To put together a solid framework for dealing with tokens, with sensiblybalanced security and ease of use, while drawing on lessons from early successh*ts (notably the original OAuth),engineers from the internet community devised OAuth 2.0 and published it asRFC 6749 in2012.

Key aspects in the OAuth 2.0 framework were deliberately kept open-ended andextensible. The base RFC 6749 specifies four securityroles and introduces fourways, called authorisation grants,for clients to obtain an access token. The rest, such as what goes inside thetoken, was left for implementers or future extensions to fillin.

2. The four roles inOAuth

OAuth 2.0 explained (2)

OAuth defines four roles, with clean separation of their concerns. This,together with the shifting of security-related complexity into a dedicatedauthorisation server, makes it possible to roll out OAuth 2.0 protectedapplications and services quickly and with consistent securityproperties.

OAuth 2.0 explained (3)

Resourceowner

The end-user. The term reflects OAuth's originalpurpose, giving 3rd party software access on a user'sbehalf. Other scenarios are alsopossible.

OAuth 2.0 explained (4)

Resourceserver

The protected asset, typically a web API, which requires a tokenin order to be accessed. The token validation logic aims to beminimal and can also bestateless.

OAuth 2.0 explained (5)

Client

The application -- web, mobile, desktop, or device-based, thatneeds to obtain a token to access the resource server.The client-side OAuth logic is intended to be simple andminimal.

OAuth 2.0 explained (6)

Authorisationserver

Dedicated server for issuing access tokens to the client, afterauthenticating the end-user and obtaining authorisation, from theend-user or based on somepolicy.

3. How can a client obtain atoken?

OAuth 2.0 explained (7)

In order to obtain an access token the client needs to present a valid grant(credential) to the authorisationserver.

If there's one thing that often daunts the newcomer to OAuth 2.0, it'sselecting a suitable grant for their application. The choice becomes obvious ifyou know the type of client (web, mobile, etc) youhave.

Here is a roughguide:

Grant typeClient type / Use case
Authorisation codeIntended for traditional web applications with a backend as well asnative (mobile or desktop) applications to take advantage of singlesign-on via the system browser.
ImplicitIntended for browser-based (JavaScript) applications without abackend.
PasswordFor trusted native clients where the application and theauthorisation server belong to the same provider.
Client credentialsFor clients, such as web services, acting on their own behalf.
Refresh tokenA special grant to let clients refresh their access token withouthaving to go through the steps of a code orpassword grant again.
SAML 2.0 bearerLets a client in possession of a SAML 2.0 assertion (sign-in token)exchange it for an OAuth 2.0 access token.
JWT bearerLets a client in possession of a JSON Web Token (JWT) assertionfrom one security domain exchange it for an OAuth 2.0 access tokenin another domain.
DeviceFor devices without a browser or with constrained input, such as asmart TV, media console, printer, etc.
Token exchangeLets applications and services obtain an access token in delegationand impersonation scenarios.

3.1 Authorisation code flowexample

OAuth 2.0 explained (8)

We will now go through an example of a client obtaining an access token from anOAuth 2.0 authorisation server, using the authorisation codegrant. This grant is intendedprimarily for webapplications.

The client needs to perform two steps to obtain the token, the first involvingthe browser, the second a back-channel request. That's why this series of stepsis also called the codeflow.

Step 1Step 2
Purpose
  1. Authenticate theuser
  2. Obtain the user'sauthorisation
  1. Authenticate the client(optional)
  2. Exchange code fortoken(s)
RequestFront-channel
(browser redirection)
Back-channel
(client to authorisation server)
ServerendpointAuthorisation endpointToken endpoint
On successAuthorisation code
(step 2 input)
Access token
Refresh token (optional)

Code flow: Step1

The client initiates the code flow by redirecting the browser to theauthorisation server with an authorisationrequest.

Example redirection to the authorisationserver:

HTTP/1.1 302 FoundLocation: https://c2id.com/login? response_type=code &scope=myapi-read%20myapi-write &client_id=s6BhdRkqt3 &state=af0ifjsldkj &redirect_uri=https%3A%2F%2Fclient.example.org%2Fcb

The authorisation request parameters are encoded in the URIquery:

  • response_type Set to code to indicate an authorisation codeflow.

  • scope Specifies the scope of the requested token. If omitted theauthorisation server may assume some defaultscope.

  • client_id The identifier of the client at the authorisation server. Thisidentifier is assigned when the client is registered with the authorisationserver, via the client registration API, a developer console, or some othermethod.

  • state Optional opaque value set by the client to maintain state betweenrequest andcallback.

  • redirect_uri The client callback URI for the authorisation response. Ifomitted the authorisation server will assume the default registeredredirection URI for theclient.

At the authorisation server, the user will typically be authenticated bychecking if they have a valid session (established by a browser cookie), and inthe absence of that, by prompting the user to login. After that the server willdetermine if the client is to be authorised or not, by asking the user fortheir consent, by applying a rule or policy, or by some othermean.

OAuth 2.0 explained (9)

The authorisation server will then call the client redirect_uri with anauthorisation code (on success) or an error code (if access was denied, orsome other erroroccurred).

HTTP/1.1 302 FoundLocation: https://client.example.org/cb? code=SplxlOBeZQQYbYS6WxSbIA &state=af0ifjsldkj

The client must validate the state parameter, and use the code to proceedto the next step - exchanging the code forthe accesstoken.

Code flow: Step2

The authorisation code is an intermediate credential, which encodes theauthorisation obtained at step 1. It istherefore opaque to the client and only has meaning to the authorisationserver. To retrieve the access token the client must submit the code to theauthorisation server, but this time with a direct back-channel request. This isdone for tworeasons:

  • To authenticate confidential clients with the authorisation server beforerevealing thetoken;
  • To deliver the token straight to the client, thus avoid exposing it to thebrowser.

The code-for-token exchange happens at the token endpoint ofthe authorisationserver:

POST /token HTTP/1.1Host: 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 authenticationOAuth 2.0 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 toauthorization_code.

  • code The code obtained from step1.

  • redirect_uri Repeats the callback URI from step1.

On success the authorisation server will return a JSONobject with the issued accesstoken:

HTTP/1.1 200 OKContent-Type: application/jsonCache-Control: no-storePragma: no-cache{ "access_token" : "SlAV32hkKG", "token_type" : "Bearer", "expires_in" : 3600, "scope" : "myapi-read myapi-write"}

The expires_in parameter informs the client for how many seconds the accesstoken will be valid. The scope parameter what powers the token actuallyhas, as some of the originally requested scope values may have been denied orothers, not explicitly requested,granted.

The JSON object can include an optional refreshtoken, which lets the clientobtain a new access token from the authorisation server without having torepeat the codeflow.

4. How can a client access a protected resource with atoken?

OAuth 2.0 explained (10)

Accessing a resource server, such as a web API, with a token is super easy. Theaccess tokens in OAuth 2.0 are commonly of typebearer, meaning the clientjust needs to pass the token with each request. The HTTP Authorization headeris the recommendedmethod.

GET /resource/v1 HTTP/1.1Host: api.example.comAuthorization: Bearer oab3thieWohyai0eoxibaequ0Owae9oh

If the resource server determines the token to be valid and not expired, itwill proceed with servicing therequest.

Else, it will return an appropriateerror in a HTTPWWW-Authenticate responseheader.

Example error for an invalid or expiredtoken:

HTTP/1.1 401 UnauthorizedWWW-Authenticate: Bearer realm="api.example.com", error="invalid_token", error_description="The access token is invalid or expired"

If the client receives an invalid_token error for an access token that usedto work, this is a signal that it must request a new one from the authorisationserver.

The usage of bearer tokens is specified in RFC6750.

Keep in mind that the bearer nature of the token means whoever has possessionof it can access the resource server. The bearer tokens must therefore beprotected:

  • First, by keeping the tokens in safe client-sidestorage.
  • By submitting the tokens over TLS /HTTPS.

Issuing short-lived tokens can mitigate the potential risk of tokenleakage.

To fix the bearer weakness of access tokens authorisation servers and clientscan implement the mTLS extension(for web and native applications) or thedPOP extension (forSPAs) which bind the token to a private key owned by the client. When an accesstoken is bound to a private key, which can be kept in a secure HSM or devicestorage, the access token is unusable without the key. Applications that needhigher security, such as in OpenBanking, therefore require mTLS securedtokens.

5. How to secure a resource server withtokens?

OAuth 2.0 explained (11)

To clear a submitted request the resource server needs to validate the token.The validation ensures thefollowing:

  1. That the access token has been issued by the authorisationserver.
  2. That the token hasn'texpired.
  3. Its scope covers therequest.

How that's done depends on the particular implementation of the access token,which is determined by the authorisation server. More on that in the nextchapter.

The required token validation logic can be easily abstracted from theunderlying resource, or retrofitted to an existing one. A reverse HTTP proxy oran API gateway can be utilised to achievethat.

Most popular web servers and frameworks, such as Apache httpd and Spring,provide some sort of module for validating incoming requests secured with abearer access token. Upon successful validation the underlying resource can beprovided with selected useful token attributes, such as the end-user'sidentity. This again is a matter ofimplementation.

6. The accesstoken

OAuth 2.0 explained (12)

The OAuth 2.0 framework doesn't prescribe a particular embodiment for accesstokens. This decision is leftto implementors for a good reason: to clients the token is just an opaquestring; their validation is a matter between the authorisation server and theresource server(s), and since they usually belong to the same provider therehasn't been enough demand to specify a standard tokenformat.

Fundamentally, there are two types of bearertoken:

Identifier-basedSelf-contained
The token represents a hard-to-guess string which is a key to arecord in the authorisation server's database. A resource servervalidates such a token by making a call to the authorisationserver's introspectionendpoint.The token encodes the entire authorisation in itself and iscryptographically protected against tampering.JSON Web Token(JWT) has become the defacto standard for self-contained tokens.

Pros / cons of identifier-basedtokens:

  • If needed, a client's or user's access tokens can berevoked with immediateeffect.
  • Token validation requires a network call which mayincrease the time to serverequests.
  • May be difficult to scale with distributedapplications.

Pros / cons of self-containedtokens:

  • Tokens can be validated on the spot, by checking theirsignature and then extracting theirpayload.
  • Easy to scale with distributedapplications.
  • The revocation of access takes effect when the issuedtokensexpire.

7. The authorisationserver

OAuth 2.0 explained (13)

The authorisation server is responsible for issuing access tokens for protectedresources under itscontrol.

OAuth gives server implementers the freedom to determine how the users getauthenticated and how the actual authorisation is obtained. The Connect2idserver takes full advantage of this freedom and provides aflexible web API to plug inauthentication factors,policies and logic to determine the issue of the tokens and their properties,such asscope.

7.1 Authenticatingusers

An authorisation server may for instance implement a combination of passwordand risk-basedauthentication, where a second factor, such as aFIDO device, is required whenthe client requests an access token for a sensitive resource or high-valuetransaction.

Delegation of the authentication to an external provider is possible, forexample by presenting a choice of popular sociallogins.

After the user is authenticated the server typically creates a session so thatsubsequent requests don't require the user tore-authenticate.

The user can be asked to re-authenticate if the fingerprint of their browserchanges or if the token scope demands greater certainty that the legitimateuser is present. This again is subject to concrete serverpolicy.

7.2Authorisation

As with end-user authentication, the process of authorisation and determiningwhat scope the issued tokens receive is implementationspecific.

Authorisation servers that issue tokens for accessing end-user data and otherresources typically render a consent form where the end-user can decide whichscopes to grant and which not to the requestingapplication.

An authorisation server in a company would consult a policy which takes intoaccount the employee's status and role to determine the token scope, skippingany consent-related interaction. The client's trust level, e.g. internalapplication vs external application, can also be a factor inthis.

7.3 Clientauthentication

OAuth defines two types ofclients, depending on their capability to authenticate securely with theauthorisationserver:

  • Confidential -- A client with credentials which uniquely identify it withthe server and which are kept confidential from the user and other entities.A web application which executes on a web server can be such aclient.

  • Public -- A clients without credentials. An application which executes ona mobile device or in a browser (SPA) can be such aclient.

Regardless of their type, all clients get a unique client_id assigned bythe authorisationserver.

Six different methods for authenticating clients have been specified so far andan authorisation server can implement any one ofthem:

MethodDescription
client_secret_basicEssentiallyHTTPbasic authentication with a shared secret. The most widelyimplemented because of its simplicity, but also with the weakestsecurity properties.
client_secret_postA variant of basic authentication where the credentials are passedas form parameters instead of in the Authorization header.
client_secret_jwtThe clientauthenticates with a JSON Web Token (JWT) secured with an HMACusing the client secret as key. Prevents leakage of the secret andlimits the time-window for replay if the request is accidentallysent over unsecured HTTP.
private_key_jwtAnother JWT-basedauthentication method, but using a private key, such as RSA orEC, which public part is registered with the authorisation server.Private key authentication limits the proliferation of secrets andalso provides a non-repudiation property.
tls_client_authThe client authenticates with aclientX.509 certificate issued from a CA authority trusted by theauthorisation server.
self_signed_tls_client_authThe client authenticates with aself-signedclient X.509 certificate. Has similar properties as the privatekey JWT method.

7.4. Authorisation serverendpoints

Core endpointsOptional endpoints
  • Authorisation
  • Token
  • Servermetadata
  • Server JWKset
  • Clientregistration
  • Pushed authorisation request(PAR)
  • Tokenintrospection
  • Tokenrevocation

7.4.1 Authorisationendpoint

This is the server endpoint where the end-user is authenticatedand authorisation is granted to the requesting client in the authorisationcode and implicit flows (grants). The remaining OAuth 2.0grants don't involve this endpoint, but the tokenenpoint.

This is also the only standard endpoint that serves requests via thefront-channel (the browser) and where users interact with theserver.

7.4.2 Tokenendpoint

The token endpoint lets the client exchange a validgrant, such as a code obtained from the authorisationendpoint, for an accesstoken.

A refresh token may also be issued, to allow the client to obtain a new accesstoken when it expires without having to resubmit a new instance of theoriginal authorisation grant, such as code or the resource owner passwordcredentials. The intent of this is to minimise the amount of end-userinteraction with the authorisation server and thus better the overallexperience.

If the client is confidential it will be required toauthenticate at the tokenendpoint.

7.4.3 Optionalendpoints

Authorisation servers can have these additionalendpoints:

Authorisation servers can have these additionalendpoints:

  • Server metadata -- JSON documentlisting the server endpoint URLs and its OAuth 2.0 features and capabilities.Clients can use this information to configure their requests to theserver.

  • Server JWK set -- JSON document with the server's public keys (typicallyRSA or EC) in JSON Web Key (JWK) format. These keys may be used to secureissued JWT-encoded access tokens and otherobjects.

  • Client registration -- RESTful webAPI for registering clients with the authorisation server. Registration maybe protected (require pre-authorisation) or open (public). The endpoint canbe enhanced to support client read, update and deleteoperations.

  • Pushed authorisation request (PAR) --enables clients to POST the payload of an authorisation request directly tothe server, the resulting handle can then be used at the authorisationendpoint to complete the request. With PAR clients can beauthenticated upfront (before the user interaction) and the authorisationrequest parameters receive integrity and confidentialityprotection.

  • Token introspection -- For lettingresource servers validate identifier-based access tokens.May also be used to validate self-contained accesstokens.

  • Token revocation -- Forletting clients notify the authorisation server that a previously obtainedrefresh or access token is no longer needed. Note this endpoint isn'tintended for revoking access for an end-user or client; that will require acustomAPI.

8.FAQ

OAuth 2.0 explained (14)

8.1 How is OpenID Connect related to OAuth2.0?

OpenID Connect is a concrete protocol for authenticatingusers, devised on top of the OAuth 2.0 framework. As such OpenID Connect isalso often called a profile of OAuth2.0.

Do not use plain OAuth to autenticate users! OpenID Connect is designedspecifically for thispurpose.

OpenID Connect introduces a new token, called ID token,to assert the user's identity and the autheneticationevent.

The access token is still used. It facilitates retrieval of consented profiledetails (called claims or attributes) from the UserInfo endpoint of the OpenIDprovider.

8.2 What other OAuth 2.0 profilesexist?

The community around the OpenID Foundation is developing other concrete profilesbesides OpenID Connect, carefully vetted by experts, to provide token-basedsecurity for a particular industry or applicationdomain:

  • FAPI -- High-security profile forfinancial-grade applications, used in Open Banking and PSD2implementations.

  • HEART -- Profile for letting individualscontrol access to their health-relateddata.

  • MODRNA -- For mobile network operatorsproviding identity services to relyingparties.

  • EAP -- Security and privacy profileintegrating token binding andFIDO.

  • iGOV -- For authenticating and sharingconsented data with public sector services across theglobe.

OAuth 2.0 explained (2024)

FAQs

What is OAuth 2.0 authentication and how does it work? ›

OAuth 2.0 enables the resource owner (i.e., the user) to give the client (i.e., the third-party application) access to their data without having to share their credentials. Instead, the credentials are shared with the authorization server, which issues an access token to the client.

What is an example of OAuth2? ›

OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives.

Why is a bad idea to use OAuth 2.0 for authentication? ›

The purpose of OAuth2 Tokens is to authorize requests at a first-party server (or API). If the third party uses the OAuth2 Access Token as proof of authentication, an attacker could easily impersonate a legitimate user.

How does OAuth2 work in the rest API? ›

OAuth 2.0 is a standard for implementing delegated authorization, and authorization is based on the access token required to access a resource. The access token can be issued for a given scope, which defines what the access token can do and what resources it can access.

Can you explain how OAuth works? ›

OAuth is an open standard for authorization. It lets users authorize third-party access to their servers without handing out their username and password. Read this blog to also find about OAuth 2.0 as an authorization framework for delegated access to web APIs.

What is the difference between basic authentication and OAuth2? ›

OAuth uses advanced user identity verification processes and is claimed to have 100% credibility. When the end-user makes an access request, a new token is created. It maintains the dependability of the process. Basic authentication offers no such facility.

Is OAuth2 obsolete? ›

It states that OAuth 2.0 is deprecated.

What problem does OAuth2 solve? ›

OAuth 2.0, which stands for “Open Authorization”, is a standard designed to allow a website or application to access resources hosted by other web apps on behalf of a user. It replaced OAuth 1.0 in 2012 and is now the de facto industry standard for online authorization.

What is the difference between OAuth and standard authentication? ›

That's because OAuth is more of an authorization framework. This keeps your credentials safe. Basic Auth, on the other hand, is an authentication protocol, which mainly focuses on proving that you're the correct person because you know things.

When should I use OAuth2? ›

If you want to enable other companies and developers to access the data of your users with their consent, then OAuth2 and OpenID Connect are essential. OAuth2 enables users to grant consent to third-party applications to access their data, providing a secure way to authenticate user requests.

Is OAuth more secure than API key? ›

While the API key mechanism is easy and well understood, OAuth provides an alternative solution, considered more secure and better suitable to support a large number of users. OAuth is a way to separate the Authentication Process from the Access to the Resource and therefore limit the exposure of the credentials.

What is the difference between OAuth and JWT? ›

JWT is suitable for stateless applications, as it allows the application to authenticate users and authorize access to resources without maintaining a session state on the server. OAuth, on the other hand, maintains a session state on the server and uses a unique token to grant access to the user's resources.

What is the difference between OAuth2 and 2FA? ›

OAuth2 is for "Server Site Authorization" of certain parameter(s) access (designated by Server site) given to a requesting entity (or App). Whereas 2FA is about Authenticating an Account Owner entity logging into an Account on the Server Site (with full owner access).

What is the difference between SSO and OAuth? ›

With OAuth you don't give the user access, rather the user gives you permission to access another app on their behalf. With SSO, you give the user access to your app. Use OAuth if: You're building an app that needs to access or modify users' data on another app.

What are the types of authentication in OAuth2? ›

The core OAuth 2.0 specification defines the "client password" (e.g. client secret) client authentication type, which defines the client_secret parameter as well as the method of including the client secret in the HTTP Authorization header. These are most common forms of client authentication.

Top Articles
Tron Bonne
Eight ways to stop your keyless car getting stolen
Lakers Game Summary
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Splunk Stats Count By Hour
Federal Fusion 308 165 Grain Ballistics Chart
Craigslist Portales
Coffman Memorial Union | U of M Bookstores
Txtvrfy Sheridan Wy
The Potter Enterprise from Coudersport, Pennsylvania
Nyuonsite
Mivf Mdcalc
Craigslist Greenville Craigslist
Driving Directions To Atlanta
Teenleaks Discord
SXSW Film & TV Alumni Releases – July & August 2024
Sport-News heute – Schweiz & International | aktuell im Ticker
Stardew Expanded Wiki
Fort Mccoy Fire Map
Little Caesars 92Nd And Pecos
Wbiw Weather Watchers
About My Father Showtimes Near Copper Creek 9
SOGo Groupware - Rechenzentrum Universität Osnabrück
Gillette Craigslist
Visit the UK as a Standard Visitor
Tripcheck Oregon Map
Otis Offender Michigan
Graphic Look Inside Jeffrey Dresser
Plato's Closet Mansfield Ohio
2015 Chevrolet Silverado 1500 for sale - Houston, TX - craigslist
The Ride | Rotten Tomatoes
Truckers Report Forums
Helloid Worthington Login
Ljw Obits
Craigs List Stockton
Can You Buy Pedialyte On Food Stamps
20 Best Things to Do in Thousand Oaks, CA - Travel Lens
Game8 Silver Wolf
Pp503063
Myanswers Com Abc Resources
8 Ball Pool Unblocked Cool Math Games
2020 Can-Am DS 90 X Vs 2020 Honda TRX90X: By the Numbers
T&Cs | Hollywood Bowl
Alba Baptista Bikini, Ethnicity, Marriage, Wedding, Father, Shower, Nazi
Ts In Baton Rouge
Cvs Coit And Alpha
Jimmy John's Near Me Open
25 Hotels TRULY CLOSEST to Woollett Aquatics Center, Irvine, CA
Ajpw Sugar Glider Worth
Congressional hopeful Aisha Mills sees district as an economical model
Morgan State University Receives $20.9 Million NIH/NIMHD Grant to Expand Groundbreaking Research on Urban Health Disparities
Escape From Tarkov Supply Plans Therapist Quest Guide
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 5662

Rating: 4.3 / 5 (64 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.