.NET

Policy-based Authorization in ASP.NET 4

By February 4, 2019 No Comments

Story

I decide to implement Single-SignOn on several existing and newly created projects. Therefore, I have to secure most of them with Auth Server, based on Identity Server and Asp.Net Core Identity. These projects are written on different technologies. I don’t prefer to rewrite anything, so I have to change just the authentication and authorization. This have to be easy considering the simplicity of the already implemented Basic Authentication.

The projects and technologies behind them are:

  • SPA Application written on Angular 6
  • SPA Application written on Angular 1
  • ASP.NET WebAPI written on ASP.NET 4

Searching for a solution

I wanted to protect my endpoints with Policy-Based Authorization and I was searching in google for solutions and implementation for ASP.NET 4, but actually I don’t find anything. I was surprised, because there is no way to be the first one trying to use Policy-based authorization in the ASP.NET 4. Actually, I found several posts how to implement something similar and I was just ready to start implementing a custom solution. I don’t know why, but I decided to search in NuGet with keywords “claims” and “policy” to see is there any package that could help me.

Evrica! There is a Owin Authorization package implemented by DavidParks8. Luckily, the description catch my eyes: “Backport of Asp.Net core’s policy based authorization to Asp.Net 4”. This is exactly what I needed.

I started testing this library immediately and everything seems work fine. There is more that 15000 downloads and regular releases, so there is no reason to not use it.

You can use MVC or WebApi package, depending on what you need:

Configuration

You are able to use policies, claims in requirements in WebApi and MVC part of .NET Framework 4. Here is the example of configuration of a policy-based authorization in Owin WebApi. The example bellow shows how to configure it into OWIN-based WebApi.


using Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security.Authorization.Infrastructure;
using System.IdentityModel.Claims;

[assembly: OwinStartup(typeof(Startup))]
namespace Concep.Platform.WebApi.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseAuthorization(options =>
            {
                options.AddPolicy("AbleToCreateUser", policy => policy.RequireClaim(JwtClaimTypes.Role, "Manager"));
            });
        }
        
    }
}

Attribute Usage

Here we have a little difference. Insted of using well-known Authorize attribute, we have to use ResourceAuthorize. The usage is in the same way:


using Microsoft.Owin.Security.Authorization.WebApi;
using Microsoft.Owin.Security.Authorization;

public class UserManagementController : ApiController 
{
    [ResourceAuthorize(Policy = "AbleToCreateUser")]
    public IHttpActionResult CreateUser()
    {
    }
}

Leave a Reply