Coding adventures with Happy results

Securing .Net Framework 4.5 with identity server 4

Tuesday, March 10, 2020 | 4:06:46 PM | C#

A few days ago I’ve been asked to provide a sample on how to secure a C# Web API using Dot Net Framework  and Identity Server 4.

In this Post, I’ll demonstrate what you need to install in order to secure an API  with Identity Server 4 using the OWIN middleware.

Creating The Project

From the menu select File > New Project

In the New Project Dialog create an ASP .NET Web Application (.NET Framework). In the framework selection, you can choose .Net Framework 4.5 and above.

 

In the ASP.NET Template dialog select Web API with No Authentication

 

 

The template will create some sample endpoint for us in the Values Controller.

 

We can create request in postman to test the functionality. As a result, the endpoint has no authorization handler and will respond with status code 200 and a array of strings in the response body.

Configuring OWIN Middleware

Next, we need to configure OWIN middleware, but first, let us install our NuGet packages.

Installing Nuget Packages

Right-click on the project and select Manage NuGet Packages

Install the following Nuget packages:

-OWIN

-Microsoft.Owin

-Microsoft.Owin.Host.SystemWeb

Next, we need to install the authentication handler that will validate the tokens

The access token Authentication handler for identity server 4 that allows accepting both JWTs and reference tokens is compatible with Asp core projects.  For this reason, will be using identityServer3.AccessTokenValidation package instead. The identityServer3.AccessTokenValidation will validate incoming tokens and works with the Owin middleware that is supported for .Net Full projects.

 

-IdentityServer3.AccessTokenValidation

 

Warning: IdentityServer3.AccessTokenValidation will install the dependency package IdentityModel. Do not update to latest version

Configuring the Authentication Handler

We are now ready to configure the Authentication Handler. First, we simply need to create a new OWIN Startup class and register the Token authentication handler for identity server.

Right-click on the project and select Add -> New Item

in the Add New Dialog, type Start in search , select OWIN Startup class from the list and press Add

Open the newly created startup class. Will be using the Identity Server clients and endpoints URLs of the demo site that can be found :

https://demo.identityserver.io/ 

 

Modify the Startup.cs to match with the following code. You need to replace client id, client secret, scope and authority with your authorization server later.

 public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
                JwtSecurityTokenHandler.InboundClaimTypeMap.Clear();
                app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions()
                {
                    Authority = "https://demo.identityserver.io",
                    ClientId = "api",
                    ClientSecret = "secret",
                    RequiredScopes = new[] { "api" },
                    ValidationMode = ValidationMode.ValidationEndpoint
                });  
        }
    }

 

Securing The Endpoints

At this point, we have register  Identity Server Bearer Token Authentication but our API is still accepting requests without Authorization.  Securing API can be done by adding the [Authorize] attribute in a Controller. This will apply security to the entire controller and endpoints.

Alternately we can apply security to a specific Endpoint or Endpoints.

And finally, we can simply secure the entire application by register the Authorization Attribute globally. This can be done by edit the app_start\WebApiConfig.cs file and add a new filter:

 

  public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
         

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            System.Web.Http.GlobalConfiguration.Configure((httpConfig) =>
            {
                httpConfig.Filters.Add(new AuthorizeAttribute());
            });
        }
    }

 

Testing

Performing again a GET request in api/values endpoint will now respond 401 unauthorize with body    "Message": "Authorization has been denied for this request."

This means that endpoint will check for an Authorization Header with a valid token.

Requesting a Token

We can request a token by clicking the tab "Authorization". In type select OAuth 2.0 and click Get New Access Token button on the right screen.

In the Get New Access Token dialog, enter the following values and press request token

In the Manage token dialog press use Token

 

We are now getting response status 200 while using token in Request Headers

 

 

 I highly recommended reading my other posts about OAuth2 & JWT Tokens and OpenID Connect protocol

 

Until next time,

Happy Coding!