Data privacy in KAPTL applications

Stas Demchuk

by Stas Demchuk on 10/30/2015

Data privacy in KAPTL

Implementing authorization in enterprise applications can be quite tricky. KAPTL can be used to create a scaffold of your next awesome app and take away all the routine from you, but we decided to leave the most interesting part to you.

We want to recommend a way to implement authorization using the code you generated with KAPTL. Let's look at how we can do this on all the frameworks we offer at the moment:

ASP.NET MVC

ASP.NET MVC has a nifty attribute that can help you restrict access to your controllers and methods: [Authorize]. You can use it allow users with proper roles access the private data. Just add the [Authorize(Roles = "COMMA_SEPARATED_LIST_OF_ROLES")] to the controller or a method and unauthorized users will be redirected to Access Denied page.

There is also a Seed method in ApplicationDbMigrationConfiguration.cs, which you can use to create the roles you need for your app without having to manually create them in the database. Here is an example:

var applicationRole = new ApplicationRole("admin");

if (context.Roles.All(role => role.Name != applicationRole.Name))
{
    context.Roles.Add(applicationRole);
    context.SaveChanges();
}

Sails.js

Sails is built on top of Express, which gives us the ability to use middlewares like Passport to create our own super secure authentication and authorization system. You can also use config/policies.js to manage user access to either the entire app or a specific controller and even a specific action. A nice tutorial on how to wire up sails with passport can be found here.

To manage permissions for different roles, you can use sails-permissions. Here is an example of adding this module to your app and creating a role with it.

AngularJS

AngularJS also has a lot of options to implement roles and permissions. Basically, you just need to add a response interceptor to track 401 Unauthorized or 403 Forbidden (depending on how your API works) and redirect the user to the proper view like "Access Denied" or perform another action. Here is an example of an interceptor:

module.factory('AuthInterceptor', ['$location', function($location) {  
    var AuthInterceptor = {
        responseError: function(response) {
            if (response.status == 401) { // or 403, depending on how the API works
                // do some preparations, like saving the previous URL to use it
                // on the back button, etc.
                $location.path('/accessDenied');
            }
        }
    };
    return AuthInterceptor;
}]);
module.config(['$httpProvider', function($httpProvider) {  
    $httpProvider.interceptors.push('AuthInterceptor');
}]);

There are a few modules out there that can help you implement this faster, like angular-acl and angular-permission.

Have any problems or questions? Let us know in the comments!