1. What is OAuth2

In the traditional client-server authentication model, the client requests an access-restricted or protected resource on the server by authenticating with the server using the resource owner’s credentials. [RFC6749]

In order to provide third-party applications access to restricted resources, the resource owner shares its credentials with the third party.

This creates several problems and limitations:

  • Third-party applications are required to store the resource owner’s credentials for future use, typically a password in clear-text.

  • Servers are required to support password authentication, despite the security weaknesses inherent in passwords.

  • Third-party applications gain overly broad access to the resource owner’s protected resources, leaving resource owners without any ability to restrict duration or access to a limited subset of resources.

  • Resource owners cannot revoke access to an individual third party without revoking access to all third parties, and must do so by changing the third party’s password.

  • Compromise of any third-party application results in compromise of the end-user’s password and all of the data protected by that password.

OAuth addresses these issues by introducing an authorization layer and separating the role of the client from that of the resource owner. In OAuth, the client requests access to resources controlled by the resource owner and hosted by the resource server, and is issued a different set of credentials than those of the resource owner.

Instead of using the resource owner’s credentials to access protected resources, the client obtains an access token — a string denoting a specific scope, lifetime, and other access attributes. Access tokens are issued to third-party clients by an authorization server with the approval of the resource owner. The client uses the access token to access the protected resources hosted by the resource server.

For example, an end-user (resource owner) can grant a printing service (client) access to her protected photos stored at a photo-sharing service (resource server), without sharing her username and password with the printing service. Instead, she authenticates directly with a server trusted by the photo-sharing service (authorization server), which issues the printing service delegation-specific credentials (access token).

The OAuth 2.0 authorization framework enables a third-party application to obtain limited access to an HTTP service, either on behalf of a resource owner by orchestrating an approval interaction between the resource owner and the HTTP service, or by allowing the third-party application to obtain access on its own behalf.

The steps to grant permission, or consent, are often referred to as authorization or even delegated authorization. You authorize one application to access your data, or use features in another application on your behalf, without giving them your password.

  • OAuth is about how to get a token and how to use a token.

  • OAuth is a delegation framework that provides authorization across systems.

  • OAuth replaces the password-sharing anti-pattern with a delegation protocol that’s simultaneously more secure and more usable.

  • OAuth is focused on solving a small set of problems and solving them well, which makes it a suitable component within larger security systems.

1.1. Roles

OAuth defines four roles:

  • resource owner

    An entity capable of granting access to a protected resource.

    When the resource owner is a person, it is referred to as an end-user.
  • resource server

    The server hosting the protected resources, capable of accepting and responding to protected resource requests using access tokens.

  • client

    An application making protected resource requests on behalf of the resource owner and with its authorization.

    The term "client" does not imply any particular implementation characteristics (e.g., whether the application executes on a server, a desktop, or other devices).
  • authorization server

    The server issuing access tokens to the client after successfully authenticating the resource owner and obtaining authorization.

    The authorization server may be the same server as the resource server or a separate entity. A single authorization server may issue access tokens accepted by multiple resource servers.

1.2. Protocol Flow

+--------+                               +---------------+
|        |--(A)- Authorization Request ->|   Resource    |
|        |                               |     Owner     |
|        |<-(B)-- Authorization Grant ---|               |
|        |                               +---------------+
|        |
|        |                               +---------------+
|        |--(C)-- Authorization Grant -->| Authorization |
| Client |                               |     Server    |
|        |<-(D)----- Access Token -------|               |
|        |                               +---------------+
|        |
|        |                               +---------------+
|        |--(E)----- Access Token ------>|    Resource   |
|        |                               |     Server    |
|        |<-(F)--- Protected Resource ---|               |
+--------+                               +---------------+

The abstract OAuth 2.0 flow describes the interaction between the four roles and includes the following steps:

  1. The client requests authorization from the resource owner.

    The authorization request can be made directly to the resource owner (as shown), or preferably indirectly via the authorization server as an intermediary.

  2. The client receives an authorization grant, which is a credential representing the resource owner’s authorization, expressed using one of four grant types defined in this specification (authorization code, implicit, password, client credential) or using an extension grant type.

    The authorization grant type depends on the method used by the client to request authorization and the types supported by the authorization server.

  3. The client requests an access token by authenticating with the authorization server and presenting the authorization grant.

  4. The authorization server authenticates the client and validates the authorization grant, and if valid, issues an access token.

  5. The client requests the protected resource from the resource server and authenticates by presenting the access token.

  6. The resource server validates the access token, and if valid, serves the request.

1.3. Client Types

OAuth defines two client types, based on their ability to authenticate securely with the authorization server (i.e., ability to maintain the confidentiality of their client credentials):

  • confidential

    Clients capable of maintaining the confidentiality of their credentials (e.g., client implemented on a secure server with restricted access to the client credentials), or capable of secure client authentication using other means.

  • public

    Clients incapable of maintaining the confidentiality of their credentials (e.g., clients executing on the device used by the resource owner, such as an installed native application or a web browser-based application), and incapable of secure client authentication via any other means.

This specification has been designed around the following client profiles:

  • web application

    A web application is a confidential client running on a web server. Resource owners access the client via an HTML user interface rendered in a user-agent on the device used by the resource owner. The client credentials as well as any access token issued to the client are stored on the web server and are not exposed to or accessible by the resource owner.

  • user-agent-based application

    A user-agent-based application is a public client in which the client code is downloaded from a web server and executes within a user-agent (e.g., web browser) on the device used by the resource owner. Protocol data and credentials are easily accessible (and often visible) to the resource owner. Since such applications reside within the user-agent, they can make seamless use of the user-agent capabilities when requesting authorization.

  • native application

    A native application is a public client installed and executed on the device used by the resource owner. Protocol data and credentials are accessible to the resource owner. It is assumed that any client authentication credentials included in the application can be extracted. On the other hand, dynamically issued credentials such as access tokens or refresh tokens can receive an acceptable level of protection. At a minimum, these credentials are protected from hostile servers with which the application may interact. On some platforms, these credentials might be protected from other applications residing on the same device.

1.4. Authorization Grant

An authorization grant is a credential representing the resource owner’s authorization (to access its protected resources) used by the client to obtain an access token.

This specification defines four grant types — authorization code, implicit, resource owner password credentials, and client credentials — as well as an extensibility mechanism for defining additional types. [RFC6749]

1.4.1. Authorization Code Grant

The authorization code grant type is used to obtain both access tokens and refresh tokens and is optimized for confidential clients. Since this is a redirection-based flow, the client must be capable of interacting with the resource owner’s user-agent (typically a web browser) and capable of receiving incoming requests (via redirection) from the authorization server.

+----------+
| Resource |
|   Owner  |
|          |
+----------+
     ^
     |
    (B)
+----|-----+          Client Identifier      +---------------+
|         -+----(A)-- & Redirection URI ---->|               |
|  User-   |                                 | Authorization |
|  Agent  -+----(B)-- User authenticates --->|     Server    |
|          |                                 |               |
|         -+----(C)-- Authorization Code ---<|               |
+-|----|---+                                 +---------------+
  |    |                                         ^      v
 (A)  (C)                                        |      |
  |    |                                         |      |
  ^    v                                         |      |
+---------+                                      |      |
|         |>---(D)-- Authorization Code ---------'      |
|  Client |          & Redirection URI                  |
|         |                                             |
|         |<---(E)----- Access Token -------------------'
+---------+       (w/ Optional Refresh Token)

The flow includes the following steps:

  1. The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied).

  2. The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request.

  3. Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier (in the request or during client registration). The redirection URI includes an authorization code and any local state provided by the client earlier.

  4. The client requests an access token from the authorization server’s token endpoint by including the authorization code received in the previous step. When making the request, the client authenticates with the authorization server. The client includes the redirection URI used to obtain the authorization code for verification.

  5. The authorization server authenticates the client, validates the authorization code, and ensures that the redirection URI received matches the URI used to redirect the client in step (C). If valid, the authorization server responds back with an access token and, optionally, a refresh token.

1.4.2. Implicit Grant

The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript.

Since this is a redirection-based flow, the client must be capable of interacting with the resource owner’s user-agent (typically a web browser) and capable of receiving incoming requests (via redirection) from the authorization server.

Unlike the authorization code grant type, in which the client makes separate requests for authorization and for an access token, the client receives the access token as the result of the authorization request.

The implicit grant type does not include client authentication, and relies on the presence of the resource owner and the registration of the redirection URI. Because the access token is encoded into the redirection URI, it may be exposed to the resource owner and other applications residing on the same device.

+----------+
| Resource |
|  Owner   |
|          |
+----------+
     ^
     |
    (B)
+----|-----+          Client Identifier     +---------------+
|         -+----(A)-- & Redirection URI --->|               |
|  User-   |                                | Authorization |
|  Agent  -|----(B)-- User authenticates -->|     Server    |
|          |                                |               |
|          |<---(C)--- Redirection URI ----<|               |
|          |          with Access Token     +---------------+
|          |            in Fragment
|          |                                +---------------+
|          |----(D)--- Redirection URI ---->|   Web-Hosted  |
|          |          without Fragment      |     Client    |
|          |                                |    Resource   |
|     (F)  |<---(E)------- Script ---------<|               |
|          |                                +---------------+
+-|--------+
  |    |
 (A)  (G) Access Token
  |    |
  ^    v
+---------+
|         |
|  Client |
|         |
+---------+

The flow includes the following steps:

  1. The client initiates the flow by directing the resource owner’s user-agent to the authorization endpoint. The client includes its client identifier, requested scope, local state, and a redirection URI to which the authorization server will send the user-agent back once access is granted (or denied).

  2. The authorization server authenticates the resource owner (via the user-agent) and establishes whether the resource owner grants or denies the client’s access request.

  3. Assuming the resource owner grants access, the authorization server redirects the user-agent back to the client using the redirection URI provided earlier. The redirection URI includes the access token in the URI fragment.

  4. The user-agent follows the redirection instructions by making a request to the web-hosted client resource (which does not include the fragment per [RFC2616]). The user-agent retains the fragment information locally.

  5. The web-hosted client resource returns a web page (typically an HTML document with an embedded script) capable of accessing the full redirection URI including the fragment retained by the user-agent, and extracting the access token (and other parameters) contained in the fragment.

  6. The user-agent executes the script provided by the web-hosted client resource locally, which extracts the access token.

  7. The user-agent passes the access token to the client.

1.4.3. Resource Owner Password Credentials Grant

The resource owner password credentials grant type is suitable in cases where the resource owner has a trust relationship with the client, such as the device operating system or a highly privileged application. The authorization server should take special care when enabling this grant type and only allow it when other flows are not viable.

This grant type is suitable for clients capable of obtaining the resource owner’s credentials (username and password, typically using an interactive form). It is also used to migrate existing clients using direct authentication schemes such as HTTP Basic or Digest authentication to OAuth by converting the stored credentials to an access token.

+----------+
| Resource |
|  Owner   |
|          |
+----------+
     v
     |    Resource Owner
    (A) Password Credentials
     |
     v
+---------+                                  +---------------+
|         |>--(B)---- Resource Owner ------->|               |
|         |         Password Credentials     | Authorization |
| Client  |                                  |     Server    |
|         |<--(C)---- Access Token ---------<|               |
|         |    (w/ Optional Refresh Token)   |               |
+---------+                                  +---------------+

The flow includes the following steps:

  1. The resource owner provides the client with its username and password.

  2. The client requests an access token from the authorization server’s token endpoint by including the credentials received from the resource owner. When making the request, the client authenticates with the authorization server.

  3. The authorization server authenticates the client and validates the resource owner credentials, and if valid, issues an access token.

1.4.4. Client Credentials Grant

The client can request an access token using only its client credentials (or other supported means of authentication) when the client is requesting access to the protected resources under its control, or those of another resource owner that have been previously arranged with the authorization server (the method of which is beyond the scope of this specification).

The client credentials grant type MUST only be used by confidential clients.

+---------+                                  +---------------+
|         |                                  |               |
|         |>--(A)- Client Authentication --->| Authorization |
| Client  |                                  |     Server    |
|         |<--(B)---- Access Token ---------<|               |
|         |                                  |               |
+---------+                                  +---------------+

The flow includes the following steps:

  1. The client authenticates with the authorization server and requests an access token from the token endpoint.

  2. The authorization server authenticates the client, and if valid, issues an access token.

1.5. Access Token

Access tokens are credentials used to access protected resources.

An access token is a string representing an authorization issued to the client. The string is usually opaque to the client.

Tokens represent specific scopes and durations of access, granted by the resource owner, and enforced by the resource server and authorization server.

The token may denote an identifier used to retrieve the authorization information or may self-contain the authorization information in a verifiable manner (i.e., a token string consisting of some data and a signature).

The access token provides an abstraction layer, replacing different authorization constructs (e.g., username and password) with a single token understood by the resource server.

This abstraction enables issuing access tokens more restrictive than the authorization grant used to obtain them, as well as removing the resource server’s need to understand a wide range of authentication methods.

Access tokens can have different formats, structures, and methods of utilization (e.g., cryptographic properties) based on the resource server security requirements.

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications such as [RFC6750].

1.6. Refresh Token

Refresh tokens are credentials used to obtain access tokens.

Refresh tokens are issued to the client by the authorization server and are used to obtain a new access token when the current access token becomes invalid or expires, or to obtain additional access tokens with identical or narrower scope (access tokens may have a shorter lifetime and fewer permissions than authorized by the resource owner).

Issuing a refresh token is optional at the discretion of the authorization server.

If the authorization server issues a refresh token, it is included when issuing an access token (i.e., step (D) in the above protocol flow).

A refresh token is a string representing the authorization granted to the client by the resource owner. The string is usually opaque to the client.

The token denotes an identifier used to retrieve the authorization information.

Unlike access tokens, refresh tokens are intended for use only with authorization servers and are never sent to resource servers.

  +--------+                                           +---------------+
  |        |--(A)------- Authorization Grant --------->|               |
  |        |                                           |               |
  |        |<-(B)----------- Access Token -------------|               |
  |        |               & Refresh Token             |               |
  |        |                                           |               |
  |        |                            +----------+   |               |
  |        |--(C)---- Access Token ---->|          |   |               |
  |        |                            |          |   |               |
  |        |<-(D)- Protected Resource --| Resource |   | Authorization |
  | Client |                            |  Server  |   |     Server    |
  |        |--(E)---- Access Token ---->|          |   |               |
  |        |                            |          |   |               |
  |        |<-(F)- Invalid Token Error -|          |   |               |
  |        |                            +----------+   |               |
  |        |                                           |               |
  |        |--(G)----------- Refresh Token ----------->|               |
  |        |                                           |               |
  |        |<-(H)----------- Access Token -------------|               |
  +--------+           & Optional Refresh Token        +---------------+

The flow refreshing an expired access token includes the following steps:

  1. The client requests an access token by authenticating with the authorization server and presenting an authorization grant.

  2. The authorization server authenticates the client and validates the authorization grant, and if valid, issues an access token and a refresh token.

  3. The client makes a protected resource request to the resource server by presenting the access token.

  4. The resource server validates the access token, and if valid, serves the request.

  5. Steps (C) and (D) repeat until the access token expires.

    If the client knows the access token expired, it skips to step (G); otherwise, it makes another protected resource request.

  6. Since the access token is invalid, the resource server returns an invalid token error.

  7. The client requests a new access token by authenticating with the authorization server and presenting the refresh token.

    The client authentication requirements are based on the client type and on the authorization server policies.

  8. The authorization server authenticates the client and validates the refresh token, and if valid, issues a new access token (and, optionally, a new refresh token).

1.7. OpenID Connect

OpenID Connect 1.0 is a simple identity layer on top of the OAuth 2.0 protocol. It allows Clients to verify the identity of the End-User based on the authentication performed by an Authorization Server, as well as to obtain basic profile information about the End-User in an interoperable and REST-like manner. [OIDC]

The OpenID Connect flow looks the same as OAuth. The only differences are, in the initial request, a specific scope of openid is used, and in the final exchange the client receives both an access token and an id token. [IGOID]

The primary extension that OpenID Connect makes to OAuth 2.0 to enable End-Users to be Authenticated is the ID Token data structure. [OIDCT]

The ID Token is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when using a Client, and potentially other requested Claims. The ID Token is represented as a JSON Web Token (JWT) [JWTIO].

2. What is JSON Web Token?

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS [RFC7515]) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted. [RFC7519]

The suggested pronunciation of JWT is the same as the English word "jot".

Terminology
JSON Web Token (JWT)
   A string representing a set of claims as a JSON object that is
   encoded in a JWS or JWE, enabling the claims to be digitally
   signed or MACed and/or encrypted.

JWT Claims Set
   A JSON object that contains the claims conveyed by the JWT.

Claim
   A piece of information asserted about a subject.  A claim is
   represented as a name/value pair consisting of a Claim Name and a
   Claim Value.

Claim Name
   The name portion of a claim representation.  A Claim Name is
   always a string.

Claim Value
   The value portion of a claim representation.  A Claim Value can be
   any JSON value.

Base64url Encoding [RFC7515]
   Base64 encoding using the URL- and filename-safe character set
   defined in Section 5 of RFC 4648 [RFC4648], with all trailing '='
   characters omitted (as permitted by Section 3.2) and without the
   inclusion of any line breaks, whitespace, or other additional
   characters.  Note that the base64url encoding of the empty octet
   sequence is the empty string.  (See Appendix C for notes on
   implementing base64url encoding without padding.)

2.1. JSON Web Token (JWT) Overview

JWTs represent a set of claims as a JSON object (i.e. JWT Claims Set) that is encoded in a JWS and/or JWE structure.

  • The JSON object consists of zero or more name/value pairs (or members), where the names are strings and the values are arbitrary JSON values.

    • These members are the claims represented by the JWT.

    • The member names within the JWT Claims Set are referred to as Claim Names.

      The corresponding values are referred to as Claim Values.

  • The contents of the JOSE Header describe the cryptographic operations applied to the JWT Claims Set.

    • If the JOSE Header is for a JWS, the JWT is represented as a JWS and the claims are digitally signed or MACed, with the JWT Claims Set being the JWS Payload.

    • If the JOSE Header is for a JWE, the JWT is represented as a JWE and the claims are encrypted, with the JWT Claims Set being the plaintext encrypted by the JWE.

    • A JWT may be enclosed in another JWE or JWS structure to create a Nested JWT, enabling nested signing and encryption to be performed.

A JWT is represented as a sequence of URL-safe parts separated by period (.) characters.

  • Each part contains a base64url-encoded value.

  • The number of parts in the JWT is dependent upon the representation of the resulting JWS using the JWS Compact Serialization or JWE using the JWE Compact Serialization.

2.2. What is the JSON Web Token structure?

In its compact form, JSON Web Tokens consist of three parts separated by dots (.), which are: [JWTIO]

  • Header

  • Payload

  • Signature

Therefore, a JWT typically looks like the following.

xxxxx.yyyyy.zzzzz

Let’s break down the different parts.

The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

For example:

{
  "alg": "HS256",
  "typ": "JWT"
}

Then, this JSON is Base64Url encoded to form the first part of the JWT.

$ cat header.json | jq -cj | base64 -w0 | tr -d '='
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

2.2.2. Payload

The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.

  • Registered claims

    These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims.

    Some of them are: iss (issuer), exp (expiration time), sub (subject), aud (audience), and others.

    Notice that the claim names are only three characters long as JWT is meant to be compact.
  • Public claims

    These can be defined at will by those using JWTs.

    But to avoid collisions they should be defined in the IANA JSON Web Token Registry or be defined as a URI that contains a collision resistant namespace.

  • Private claims

    These are the custom claims created to share information between parties that agree on using them and are neither registered or public claims.

An example payload could be:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

The payload is then Base64Url encoded to form the second part of the JSON Web Token.

$ cat payload.json | jq -cj | base64 -w0 | tr -d '='
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9
Do note that for signed tokens this information, though protected against tampering, is readable by anyone. Do not put secret information in the payload or header elements of a JWT unless it is encrypted.

2.2.3. Signature

To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

The signature is used to verify the message wasn’t changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.

2.2.4. Putting all together

The output is three Base64-URL strings separated by dots that can be easily passed in HTML and HTTP environments, while being more compact when compared to XML-based standards such as SAML.

The following shows a JWT that has the previous header and payload encoded, and it is signed with a secret (123456).

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.Wwu4TUUE86MPyFGhmv3D0Ct4GqkthRQDPKBwOQAAwJc

3. Microsoft identity platform

The Microsoft identity platform helps you build applications your users and customers can sign in to using their Microsoft identities or social accounts. It authorizes access to your own APIs or Microsoft APIs like Microsoft Graph.

There are several components that make up the Microsoft identity platform:

  • OAuth 2.0 and OpenID Connect standard-compliant authentication service enabling developers to authenticate several identity types, including:

    • Work or school accounts, provisioned through Azure AD

    • Personal Microsoft accounts (Skype, Xbox, Outlook.com)

    • Social or local accounts, by using Azure AD B2C

  • Open-source libraries: Microsoft Authentication Library (MSAL) and support for other standards-compliant libraries.

  • Application management portal: A registration and configuration experience in the Azure portal, along with the other Azure management capabilities.

  • Application configuration API and PowerShell: Programmatic configuration of your applications through the Microsoft Graph API and PowerShell so you can automate your DevOps tasks.

  • Developer content: Technical documentation including quickstarts, tutorials, how-to guides, and code samples.

3.1. Authentication vs. authorization [msadauthnz]

Authentication is the process of proving that you are who you say you are. This is achieved by verification of the identity of a person or device. It’s sometimes shortened to AuthN. The Microsoft identity platform uses the OpenID Connect protocol for handling authentication.

Authorization is the act of granting an authenticated party permission to do something. It specifies what data you’re allowed to access and what you can do with that data. Authorization is sometimes shortened to AuthZ. The Microsoft identity platform uses the OAuth 2.0 protocol for handling authorization.

Multifactor authentication is the act of providing an additional factor of authentication to an account. This is often used to protect against brute force attacks. It is sometimes shortened to MFA or 2FA. The Microsoft Authenticator can be used as an app for handling two-factor authentication. For more information, see multifactor authentication.

3.2. OAuth 2.0 and OpenID Connect (OIDC) in the Microsoft identity platform

3.2.1. Roles in OAuth 2.0

Four parties are generally involved in an OAuth 2.0 and OpenID Connect authentication and authorization exchange. These exchanges are often called authentication flows or auth flows. [msadouth2]

Diagram showing the OAuth 2.0 roles
  • Authorization server - The identity platform is the authorization server. Also called an identity provider or IdP, it securely handles the end-user’s information, their access, and the trust relationships between the parties in the auth flow. The authorization server issues the security tokens your apps and APIs use for granting, denying, or revoking access to resources (authorization) after the user has signed in (authenticated).

  • Client - The client in an OAuth exchange is the application requesting access to a protected resource. The client could be a web app running on a server, a single-page web app running in a user’s web browser, or a web API that calls another web API. You’ll often see the client referred to as client application, application, or app.

  • Resource owner - The resource owner in an auth flow is usually the application user, or end-user in OAuth terminology. The end-user "owns" the protected resource (their data) which your app accesses on their behalf. The resource owner can grant or deny your app (the client) access to the resources they own. For example, your app might call an external system’s API to get a user’s email address from their profile on that system. Their profile data is a resource the end-user owns on the external system, and the end-user can consent to or deny your app’s request to access their data.

  • Resource server - The resource server hosts or provides access to a resource owner’s data. Most often, the resource server is a web API fronting a data store. The resource server relies on the authorization server to perform authentication and uses information in bearer tokens issued by the authorization server to grant or deny access to resources.

3.2.2. Tokens

The parties in an authentication flow use bearer tokens to assure, verify, and authenticate a principal (user, host, or service) and to grant or deny access to protected resources (authorization). Bearer tokens in the identity platform are formatted as JSON Web Tokens (JWT).

Three types of bearer tokens are used by the identity platform as security tokens:

  • Access tokens - Access tokens are issued by the authorization server to the client application. The client passes access tokens to the resource server. Access tokens contain the permissions the client has been granted by the authorization server.

  • ID tokens - ID tokens are issued by the authorization server to the client application. Clients use ID tokens when signing in users and to get basic information about them.

  • Refresh tokens - The client uses a refresh token, or RT, to request new access and ID tokens from the authorization server. Your code should treat refresh tokens and their string content as sensitive data because they’re intended for use only by authorization server.

3.2.3. App registration

Your client app needs a way to trust the security tokens issued to it by the identity platform. The first step in establishing trust is by registering your app. When you register your app, the identity platform automatically assigns it some values, while others you configure based on the application’s type.

Two of the most commonly referenced app registration settings are:

  • Application (client) ID - Also called application ID and client ID, this value is assigned to your app by the identity platform. The client ID uniquely identifies your app in the identity platform and is included in the security tokens the platform issues.

  • Redirect URI - The authorization server uses a redirect URI to direct the resource owner’s user-agent (web browser, mobile app) to another destination after completing their interaction. For example, after the end-user authenticates with the authorization server. Not all client types use redirect URIs.

Your app’s registration also holds information about the authentication and authorization endpoints you’ll use in your code to get ID and access tokens.

3.2.4. Endpoints

The identity platform offers authentication and authorization services using standards-compliant implementations of OAuth 2.0 and OpenID Connect (OIDC) 1.0. Standards-compliant authorization servers like the identity platform provide a set of HTTP endpoints for use by the parties in an auth flow to execute the flow.

The endpoint URIs for your app are generated automatically when you register or configure your app. The endpoints you use in your app’s code depend on the application’s type and the identities (account types) it should support.

Two commonly used endpoints are the authorization endpoint and token endpoint. Here are examples of the authorize and token endpoints:

# Authorization endpoint - used by client to obtain authorization from the resource owner.
https://login.microsoftonline.com/<issuer>/oauth2/v2.0/authorize
# Token endpoint - used by client to exchange an authorization grant or refresh token for an access token.
https://login.microsoftonline.com/<issuer>/oauth2/v2.0/token

# NOTE:
#   These are examples. Endpoint URI format may vary based on application type,
#   sign-in audience, and Azure cloud instance (global or national cloud).

#   The {issuer} value in the path of the request can be used to control who can sign into the application.
#   The allowed values are **common** for both Microsoft accounts and work or school accounts,
#   **organizations** for work or school accounts only, **consumers** for Microsoft accounts only,
#   and **tenant identifiers** such as the tenant ID or domain name.

To find the endpoints for an application you’ve registered, in the Azure portal navigate to: Azure Active Directory > App registrations > <YOUR-APPLICATION> > Endpoints.

3.3. OpenID Connect on the Microsoft identity platform

OpenID Connect (OIDC) extends the OAuth 2.0 authorization protocol for use as an additional authentication protocol. You can use OIDC to enable single sign-on (SSO) between your OAuth-enabled applications by using a security token called an ID token. [msadoidc]

Swim-lane diagram showing the OpenID Connect protocol’s sign-in flow.
Figure 1. The basic OpenID Connect sign-in flow

The ID token introduced by OpenID Connect is issued by the authorization server, the Microsoft identity platform, when the client application requests one during user authentication. The ID token enables a client application to verify the identity of the user and to get other information (claims) about them.

ID tokens aren’t issued by default for an application registered with the Microsoft identity platform. ID tokens for an application are enabled by using one of the following methods:

  1. Navigate to the Azure portal and select Azure Active Directory > App registrations > <your application> > Authentication.

  2. Under Implicit grant and hybrid flows, select the ID tokens (used for implicit and hybrid flows) checkbox.

Or:

  1. Select Azure Active Directory > App registrations > <your application> > Manifest.

  2. Set oauth2AllowIdTokenImplicitFlow to true in the app registration’s application manifest.

If ID tokens are not enabled for your app and one is requested, the Microsoft identity platform returns an unsupported_response error similar to:

The provided value for the input parameter 'response_type' isn’t allowed for this client. Expected value is 'code'.

3.4. Authentication flows and application scenarios

The Microsoft identity platform supports authentication for different kinds of modern application architectures. All of the architectures are based on the industry-standard protocols OAuth 2.0 and OpenID Connect. By using the authentication libraries for the Microsoft identity platform, applications authenticate identities and acquire tokens to access protected APIs.

This article describes authentication flows and the application scenarios that they’re used in. [msadscene]

3.4.1. Application categories

Tokens can be acquired from several types of applications, including:

  • Web apps

  • Mobile apps

  • Desktop apps

  • Web APIs

Tokens can also be acquired by apps running on devices that don’t have a browser or are running on the Internet of Things (IoT).

The following sections describe the categories of applications.

3.4.1.1. Protected resources vs. client applications

Authentication scenarios involve two activities:

  • Acquiring security tokens for a protected web API: We recommend that you use the Microsoft Authentication Library (MSAL), developed and supported by Microsoft.

  • Protecting a web API or a web app: One challenge of protecting these resources is validating the security token. On some platforms, Microsoft offers middleware libraries.

3.4.1.2. With users or without users

Most authentication scenarios acquire tokens on behalf of signed-in users.

Scenarios with users

However, there are also daemon apps. In these scenarios, applications acquire tokens on behalf of themselves with no user.

Scenarios with daemon apps
3.4.1.3. Single-page, public client, and confidential client applications

Security tokens can be acquired by multiple types of applications. These applications tend to be separated into the following three categories. Each is used with different libraries and objects.

  • Single-page applications: Also known as SPAs, these are web apps in which tokens are acquired by a JavaScript or TypeScript app running in the browser. Many modern apps have a single-page application at the front end that’s primarily written in JavaScript. The application often uses a framework like Angular, React, or Vue. MSAL.js is the only Microsoft Authentication Library that supports single-page applications.

  • Public client applications: Apps in this category, like the following types, always sign in users:

    • Desktop apps that call web APIs on behalf of signed-in users

    • Mobile apps

    • Apps running on devices that don’t have a browser, like those running on IoT

  • Confidential client applications: Apps in this category include:

    • Web apps that call a web API

    • Web APIs that call a web API

    • Daemon apps, even when implemented as a console service like a Linux daemon or a Windows service

4. Keycloak

Keycloak is an open-source software product that provides identity and access management (IAM) capabilities for modern applications and services. It offers a comprehensive solution for managing user authentication, authorization, and single sign-on (SSO).

To start Keycloak from a terminal, enter the following command:

docker run \
    -d \
    --name keycloak \
    -p 8080:8080 \
    -e KC_BOOTSTRAP_ADMIN_USERNAME=admin \
    -e KC_BOOTSTRAP_ADMIN_PASSWORD=admin \
    quay.io/keycloak/keycloak:26.0.7 \
    start-dev

References