Sunday, August 18, 2019

Butterfly Effect and Problems Solving


Butterfly Effect


Butterfly effect in simple words is, something as small as flap of a butterfly wings can cause a chain of huge actions. Even a nuclear war between US and USSR (Long time ago!)

In the other way round, cause for some of the large problems and events that we experience today could be something really small as we could never imagine.

Examples of Butterfly Effect


Massive ecological changes in Yellow Stone National Park after reintroducing wolves in 1995


Courtesy of government’s predator control program, wolves went extinct from the park by mid 1900s. And that affected the balance of the entire eco system resulting number of issues. Once wolves were reintroduced in 1995 (14 of them in 1995 and another 17 in 1996) park’s entire eco system were changed within a span couple of years. Grass banks started to grow again in valleys, Forest started to grow, and number of new species were moved in and contributed to the eco system. And by the whole sequence of actions, it changed a path of a river as well. All these were started with just 14 wolves.

Watch this video on how Yellow Stone were transformed after introducing Wolves https://www.youtube.com/watch?v=ysa5OBhXz-Q

Rejection of Art application lead to World War II


In 1905 young Adolf Hitler applied to the academy of fine arts in Vienna which unfortunately were rejected twice. Somehow the Second World War happened and about 80 million people  (3% of world population by then) were paid their lives in span of 7 years.

Problem Solving in Software Engineering


Day to day job of a Software Engineer is solving problems. Before implementing a fix to problem, first thing is to solve it. The way you approach the problem, the way you breakdown the problem into pieces plays a big role in solving it. And that defines how good you as a Software Engineer.

“You can’t see the picture if you are within the frame”

You should try to think out of the box as much as possible. Take couple of steps back and try to get out of the problem as much as you can and see it in a wider angle. Then only you can see new routes towards the Answer.

Always believe in the inverse of butterfly effect. More often than not the root cause of a large problem can be a small fix as commenting a single line of code or changing logic in one single method. Changing a variable name to an appropriate one could help to improve the readability and then help to see through the problem much easier.

Be lazy and smart!

Friday, August 2, 2019

Dynamic Authorization Policies in .NetCore Identity Framework


When it comes to implementing an Authorization Engine or Permission Engine for an ASP.Net Core Web API, we can use the Identity Framework.  Please refer my previous post on Claim based Authorization in Asp.Net Core.
If you have a basic understanding on how claim based authorization works, you should be already familiar with security policies. Security Policies are used to decorate controller action to control authorization, and the policy defines what is required to satisfy the policy. Usually a Policy check if the logged in user has certain claims (one or multiple) with him. Normally one or few claims required to satisfy a policy and most of the time it is one claim per policy.  
If your authorization engine is mainly based on one claim per policy (or if you can model it in such away), you will notice that you will have to write large amount of security policies where each policy is checking whether the user has a certain claim. This is a repetitive and annoying task which you would have to spend considerable amount of time.

What if Possible to Decorate Controller Actions with Claim Itself?


That’s sounds nice. Instead of writing hundreds of security policies, just decorate the actions with the claim that required to access it. But unfortunately it is not supported by Identity Framework by default. It only allows to specify the policy names or the role names.

Is There a Workaround?


Yes! Identity framework supports creating dynamic policies by implementing IAuthorizationPolicyProvider and AuthorizeAttribute

Custom Authorize Attribute

internal class ClaimAuthorizeAttribute : AuthorizeAttribute
{
    const string POLICY_PREFIX = "REQUIRE_CLAIM_";

    public ClaimAuthorizeAttribute(string claim) => Claim = claim;

    public string Claim
    {
        get
        {
            var claim = Policy.Substring(POLICY_PREFIX.Length);
            return claim;
        }
        set
        {
            Policy = $"{POLICY_PREFIX}{value}";
        }
    }
}

Custom Authorization Policy Provider


internal class CustomAuthorizationPolicyProvider : IAuthorizationPolicyProvider
{
    const string POLICY_PREFIX = "REQUIRE_CLAIM_";

    public Task GetDefaultPolicyAsync()
    {
               return Task.FromResult(new AuthorizationPolicyBuilder()
                       .RequireAuthenticatedUser().Build());
    }

    public Task GetPolicyAsync(string policyName)
    {
       var requiredClaim = policyName.Substring(POLICY_PREFIX.Length);

       var policy = new AuthorizationPolicyBuilder();

       policy.RequireClaim(CustomClaimTypes.Permission, requiredClaim);

       return Task.FromResult(policy.Build());
         }
 }

Tell .Net Core to Use Our Custom Policy Provider Instead the Default One


In the startup.cs add the following line in ConfigureServices() Method.
services.AddSingleton();

Decorating Controller Action with the New Attribute


[ClaimAuthorize(“DRIVER_VIEW”)]
public async Task GetAsync(string id)
{
    var result = await _driverService.GetDriverWithPostCodesAsync(id);
    return result;
}

Summary


Using this approach you can simply outsource the burden of creating hundreds of authorization policies. Eventually that will save large amount of development time of your team. Also the code will be nice and clean.