OAuth2 and OpenID Connect - Gary-Moore/developmentwiki GitHub Wiki

OAuth2

OAuth 2.0 is the industry-standard protocol for authorization. OAuth 2.0 supersedes the work done on the original OAuth protocol created in 2006. OAuth 2.0 focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices.

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.

OpenID Connect allows clients of all types, including Web-based, mobile, and JavaScript clients, to request and receive information about authenticated sessions and end-users. The specification suite is extensible, allowing participants to use optional features such as encryption of identity data, discovery of OpenID Providers, and session management, when it makes sense for them.

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-openid-connect-code

Identity Provider

An identity provider is a system entity that creates, maintains, and manages identity information for principals while providing authentication services to relying party applications within a federation or distributed network.

An identity provider offers user authentication as a service. Relying party applications, such as web applications, outsource the user authentication step to a trusted identity provider. Such a relying party application is said to be federated, that is, it consumes federated identity.

An identity provider is “a trusted provider that lets you use single sign-on (SSO) to access other websites.” SSO enhances usability by reducing password fatigue. It also provides better security by decreasing the potential attack surface.

Within OpenID Connect, an identity provider is a special type of OAuth 2.0 authorization server. Specifically, a system entity called an OpenID Provider issues JSON-formatted identity tokens to OIDC relying parties via a RESTful HTTP API.

OpenID Connect metadata document

OpenID Connect describes a metadata document that contains most of the information required for an app to perform sign-in. This includes information such as the URLs to use and the location of the service's public signing keys. The OpenID Connect metadata document can be found at:

https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration

Send the sign-in request

When your web application needs to authenticate the user, it must direct the user to the /authorize endpoint. This request is similar to the first leg of the OAuth 2.0 Authorization Code Flow, with a few important distinctions:

The request must include the scope openid in the scope parameter. The response_type parameter must include id_token. The request must include the nonce parameter.

Authorisation Endpoint

The authorize endpoint can be used to request tokens or authorization codes via the browser. This process typically involves authentication of the end-user and optionally consent.

The authorization code flow begins with the client directing the user to the /authorize endpoint. In this request, the client indicates the permissions it needs to acquire from the user. You can get the OAuth 2.0 authorization endpoint for your tenant by selecting App registrations > Endpoints in the Azure portal.

https://login.microsoftonline.com/{tenant}/oauth2/authorize

Token Endpoint

Now that you've acquired an authorization code and have been granted permission by the user, you can redeem the code for an access token to the desired resource, by sending a POST request to the /token endpoint:

https://login.microsoftonline.com/{tenant}/oauth2/token

Azure AD returns an access token upon a successful response. To minimize network calls from the client application and their associated latency, the client application should cache access tokens for the token lifetime that is specified in the OAuth 2.0 response. To determine the token lifetime, use either the expires_in or expires_on parameter values.

If a web API resource returns an invalid_token error code, this might indicate that the resource has determined that the token is expired. If the client and resource clock times are different (known as a "time skew"), the resource might consider the token to be expired before the token is cleared from the client cache. If this occurs, clear the token from the cache, even if it is still within its calculated lifetime.

Workflows

Authorization Code Flow

The authorization code flow returns an authorization code (like it says on the tin) that can then be exchanged for an identity token and/or access token. This requires client authentication using a client id and secret to retrieve the tokens from the back end and has the benefit of not exposing tokens to the user agent (i.e. a web browser). This flow allows for long lived access (through the use of refresh tokens). Clients using this flow must be able to maintain a secret.

This flow obtains the authorization code from the authorization endpoint and all tokens are returned from the token endpoint.

Implicit Flow

The implicit flow requests tokens without explicit client authentication, instead using the redirect URI to verify the client identity. Because of this, refresh tokens are not allowed, nor is this flow suitable for long lived access tokens. From the client application's point of view, this is the simplest to implement, as there is only one round trip to the OpenID Connect Provider.

This flow obtains all tokens from the authorization endpoint.

Hybrid Flow

The hybrid flow is a combination of aspects from the previous two. This flow allows the client to make immediate use of an identity token and retrieve an authorization code via one round trip to the authentication server. This can be used for long lived access (again, through the use of refresh tokens). Clients using this flow must be able to maintain a secret.

This flow can obtain an authorization code and tokens from the authorization endpoint, and can also request tokens from the token endpoint.

Setting Up OpenID Connect with Azure AD

Asp.net Core

Add the Microsoft.AspNetCore.Authentication.AzureAD.UI nuget package to the solution.

In the startup class add the following to the ConfigureServices method:

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.AddMvc(options =>
{
     var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
     options.Filters.Add(new AuthorizeFilter(policy));
 })

And set the following in the configure Method:

app.UseAuthentication();

This sets up the authentication options and applies authorization.

Configuration and App registration

Create an app registration in Azure AD and then Set the following in the app settings:

"AzureAD": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "{tenant domain}",
    "TenantId": "{tenant Id}",
    "ClientId": "{application id}",
    "CallbackPath": "/signin-oidc"
  },

Ensure the reply url (sign on url) is in the following format:

http://myapp.com/signin-oidc

https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x?view=aspnetcore-2.1

https://azure.microsoft.com/en-gb/resources/samples/active-directory-dotnet-webapp-openidconnect-aspnetcore/

https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-developers-guide

ASP.Net MVC

Setup the app to use OWIN and install the following nuget packages:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

https://docs.microsoft.com/en-gb/azure/active-directory/develop/GuidedSetups/active-directory-aspnetwebapp-v1