Creating Custom OAuth Middleware for MVC 5

Comments 5

Share to social media

OAuth allows web users to prove their identity when using a web site without having to create a subscription or supply details or credentials, using instead their Google, LinkedIn, Facebook or Twitter accounts. If a Web site implements OAuth, then visitors can use the site without worrying about their access credentials being compromised.

ASP.Net MVC 5 enables OAuth2 authentication. Although Google, LinkedIn, Facebook or Twitter authentication providers ship ‘out of the box’, there are many others that are not included. In order to add an additional authentication provider to an application you will need custom authentication middleware. In this article we’ll learn about the processes and components required for custom authentication in MVC 5.

You can read more about MVC’s default providers in Dino Esposito’s Social Login in ASP.NET MVC article.

MVC 5 authentication changes

Because MVC 5 is built on Katana, an implementation of the OWIN specification, authentication has changed significantly and the authentication providers written for previous versions of MVC will not work. They will need to be rewritten as OWIN middleware. OWIN is a new modular interface for handling HTTP requests designed to decouple the server and application.

OWIN Middleware Components

OWIN Middleware Components or OMCs are modules written to work with Katana at a low level and are used to respond to HTTP requests. OMCs implement the IAppBuilder interface and are added to the OWIN pipeline using the I AppBuilder.Use method. The OWIN pipeline in the Katana runtime will process OMCs in the order they were registered in the application.

For more detailed information about OMCs in general, please refer to the Katana overview OWIN Middleware in the IIS integrated pipeline in the ASP.Net documentation

With MVC 5, authentication middleware are registered with the application when the Startup.ConfigAuth method is executed. When MVC executes the ConfigAuth method the applications instance of the IAppBuilder is exposed and passed to the authentication middleware.

In the Microsoft MVC source code for Facebook authentication; you can see the UseFacebookAuthentication helper used to register the middleware via app.Use.

Each authentication middleware provides an API for setting up the middleware options and invoking IAppBuilder.Use . The Use [ AuthType ] Authentication extension methods are primarily syntactic sugar designed for easy setup.

This excerpt from a standard MVC application’s App_Start\Startup.Auth.cs file shows how OAuth providers are initialized.

OAuth Process


The OAuth process is complex and requires several interactions with the user, browser, application/middleware, and the OAuth service. Let’s look at an overview of the process grouped into five main steps:

  • A request requires user authentication (http 401 unauthorized)
  • The browser is redirected to the third party authorization page
  • The user clicks “Allow” and the service redirects the browser back to the application with an access code.
  • The middleware uses the access code to gain access to the user’s information and generates a Claims Identity containing basic user information.
  • The application receives the Claims Identity for creating a user profile, and login.

OAuth process details

There are many detailed sub processes that must occur in each of these steps. Since we are creating a custom authentication middleware we will be responsible for handling each detail of the entire authentication process.

The process begins when the user is required to authenticate with the application. In MVC this is when a user reaches an endpoint that has been marked [Authorize] . The application will redirect the user to the Account/Login action and the Login view will be displayed. All authentication providers registered with the application will be presented for the user to choose from.


When the user clicks on a provider, the application will respond with a 401 response containing the provider type (ex: “facebook”) in the AuthenticationResponseChallenge . At this point the ApplyResponseChallengeAsync method is invoked on the middleware to intercept the response. If the response is a (401 unauthorized) with the matching provider type then the response will be changed to a redirect to the authentication provider’s endpoint.

Once the user has reached the authentication provider they will prompted by the third party to allow the application access to user details such as: user name, email and ID (service APIs may vary). When the user chooses to allow the application access, the service will redirect the user to the applications callback path.

It’s important to differentiate the callback path of the middleware (ex: application/signin-authType) and application (ex: application/Account/ExternalLoginCallback). The callback path is not the ExternalLoginCallback action on the Account controller but instead a path used for the middleware to identify a request coming back from a third party service. The middleware is invoked before application routing occurs.

When the request reaches the application, the middleware will intercept the request. The request will contain the callback path, the authorization code needed for retrieving an authentication token, and other information required by the API such as: client id, client secret, and CSRF tokens.

After obtaining the authorization code the middleware will contact the authentication service again to request an authentication token. Once the middleware and application have the authentication token the third party API can be used to retrieve information about the user. A request will be sent to the AuthenticationEndpoint with any headers and values required by the API.

The service will respond with a success status and contain the authentication token. Depending on the API and addition request may be required to obtain detailed information about the user. Once the user’s information has been collected and ClaimsIdentity is created, the ClaimsIdentity will be returned to the application via the AccountController.ExternalLoginCallback action. The application now has the user’s information and can create a user profile and login the user.


The diagram shows the authentication process in reference to the middleware and application.

OAuth Components

OAuth middleware consists of several components that work together to complete the OAuth process. The following classes are used to configure and register the middleware, instantiate the provider, and handle authentication. Each component is described below in the order they are required by the authentication process.


An authentication extensions class is used to create an API used for registering the middleware with the OWIN pipeline. The class Custom AuthenticationExtensions extends the IAppBuilder by providing a UseCustom Authentication method. The U seCustom Authentication method gives other developers an easy to use API for initializing the middleware and its options while registering the middleware with Katana.


CustomAuthentication Options specifies configuration for the authentication process and objects used throughout the authentication process. This includes service endpoints and API parameters such as client ID and client secret. CustomAuthentication Options inherits from the AuthenticationOptions base class. The authentication options associated with a custom middleware are often referenced by other components as TOptions .


CustomAuthenticationMiddleware inherits from AuthenticationMiddleware < TOptions > where TOptions is CustomAuthenticationOptions . CustomAuthenticationMiddleware initializes the CustomAuthenticationProvider , CustomAuthenticationHandler , and ILogger < CustomAuthenticationMiddleware > . The AuthenticationMiddleware itself is rather sparse because most of the work has been abstracted away into the AuthenticationHandler .


Custom AuthenticationProvider specifies the delegates that are called during authentication. OnAuthenticated is invoked when a user is successfully authenticated. OnReturnEndpoint , is invoked before the ClaimsIdentity is saved and the browser redirects to the originally requested URL.

Authenticated Context

CustomAuthenticationContenxt inherits from BaseContext . The AuthenticationContext receives and parses the user information retrieved from the authentication service. The AuthenticationContext properties contain the login session information as well as details about the user that logged in including the ClaimsIdentity and AuthenticationProperties .


CustomReturnEndpointContext inherits from ReturnEndpointContext . ReturnEndpointContext provides information about the OWIN context and holds the authentication ticket information.


The CustomAuthenticationHandler is responsible for the bulk of the authentication process. CustomAuthenticationHandler inherits from AuthenticationHandler < CustomAuthenticationOptions > and has three methods that need to be overridden: AuthenticateCoreAsync , ApplyResponseChallengeAsync , and InvokeAsync .


This method is invoked during an HTTP response. The method will look for a response that requires authentication (401 unauthorized) and a matching authentication type. When this criteria is met the method will be responsible for creating the CSFR token and redirecting the browser to the authentication endpoint.


The InvokeAsync method is used to detect a callback request from the authentication service. InvokeAsync will check the request for a path that matches callback path (ex: /signin-facebook). When the callback path is detected the method will invoke AuthenticateAsyncCore via AuthenticateAsnyc . Once AuthenticateAsyncCore is complete the method will create a ReturnEndpointContext , grant the ClaimsIdentity and complete the request by redirecting to the application’s ExternalLoginCallback action.


AuthenticateCoreAsync performs several tasks. The method will validate the CSRF token insuring the security of the request. Next, the access token is request from the authentication service and if needed a second request is made for additional user information. Once the user’s information is collected the authentication context and ClaimsIdentity are generated. Finally, the OnAuthenticated method is called and given the AuthenticationContext .

Conclusion & Open Source

By understanding the processes and components involved in authentication using Katana, you will be able to create authentication middleware for any OAuth service provider. Although the authentication process is complex and has many components, there are several open source implementations available as a reference. The open source projects listed below are excellent references for jumpstarting development of your own middleware.

The Katana Project on Codeplex (Microsoft)

OwinOAuthProviders project on GitHub