Monday, February 5, 2018

Authorization

Authorization determines whether an identity should be granted access to a specific resource or not. This can be implemented/handled in different ways as below.

In ASP.NET: There are two ways to authorize access to a given resource:
  • File Authorization:

    This is performed by using FileAuthorizationModule which checks the access control list (ACL) of .aspx or .asmx handler file to determine whether user should have access to the resource. ACL permissions are verified for the user's Windows identity (if Windows Authentication is enabled) or for the Windows identity of the ASP.NET process

    FileAuthorizationModule verifies that the user has permission to access the requested file. This class cannot be inherited and below is the syntax of using this class

    public sealed class FileAuthorizationModule : System.Web.IHttpModule

    This module provides authorization services against file-system access-control lists (ACLs). When the mode attribute of the configuration element is set to windows then the WindowsAuthenticationModule is being used for the application. This modules ensures that the requesting user is allowed read or write access to the resource, depending on the request verb, before executing the request.

  • URL Authorization:

    This is performed using UrlAuthorizationModule which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application for specific users or roles

    Wthe URL authorization, one can explicitly allow or deny access to a particular directory by user name or role. To do so, we need to create or have an authorization section of a configuration file. The permissions established for a directory also apply to its subdirectories, unless configuration files in a subdirectory override them.

    Rules are applied as below:

    • Rules contained in application level configuration files take precedence over inherited rules. The system determines which rule takes precedence by constructing a merged list of all rules for a URL, with the most recent rules at the head of the list
    • Given a set of merged rules for an application, ASP.NET starts at the head of the list and checks rules until the first match is found.

    Examples of configuring authorization(s):

    Syntax
    <authorization>
            < [allow][deny] users roles verbs />
    </authorization>

    Grant access to Kim and members of the Admins role, and denies access to the John identity and to all anonymous users:
    <authorization>
            < <allow users ="Kim" />
            < <allow roles ="Admins" />
            < <deny users ="John" />
            < <deny users ="?" />
    </authorization>

    Allow access to John identity and deny access to all other users:
    <authorization>
            < <allow users ="John" />
            < <deny users ="*" />
    </authorization>

    Can specify multiple entities for both the users and roles attributes by using comma-separated list:
    <authorization>
            < <allow users ="Jon, Kim, Contoso\Jane" />
    </authorization>

    Allow users to perform an HTTP GET for a resource, but allows only the Kim identify to perform a POST operation:
    <authorization>
            < <allow verbs ="GET" users="*" />
            < <allow verbs ="POST" users="Kim" />
            < <deny verbs ="POST" users="*" />
    </authorization>

In Web API: Authorization happens closer to the controller which lets one to make more granular choices while grating the access.
  • Authorization filters will run before running the controller actions. Based on the filter results user will be redirected either to a error response or to a action response
  • Using current principal from ApiController.User, one can work with current principal within controller's action
Below are the available Custom Authorization Filters:
  • AuthorizeAttribute: Extend this class to perform authorization logic based on the current user and the user's roles.
  • AuthorizationFilterAttribute: Extend this class to perform synchronous authorization logic that is not necessarily based on the current user or role
  • IAuthorizationFilter: Implement this to perform asynchronous authorization logic

In cases where you want to change the behavior based on the role, we can handle this using based on the principal. Within a controller method, you can get the current principal from the ApiController.User property. Below is an example:

public HttpResponseMessage Get()
{
          if (User.IsInRole("Administrators"))
          {
                // ...
          }
}

With this I am concluding the illustration. Feel free to share your feedback. Happy Programming !!!

Token Based Authentication

Token based authentication is a security technique that authenticates the users who attempt to log in to a server, a network, or some other secure system, using a security token provided by the server.

A Token is a piece of data created by server and contains information to identify a particular user and token validity. Token based authentication is stateless and will not store any information about user on the server or in a session. The token will contains the user's information, as well as a special token code that user can pass to the server with every method that supports authentication instead of passing username and passwords directly.

After the token is validated by the service, it is used to establish security context for the client, so the service can make authorization decisions or audit activity for successive user requests.

How Token based authentication works:

  • User provides credentials, which will be verified by server that the information is correct
  • Once server finds the match, a signed token will be sent and stored in user's local storage
  • As part of completing the authorization action, the token is attache to user's request which then be decoded and verified by server
  • A match allows the user to proceed
  • The token will be destroyed when user logs out

Advantages of using Token based authentication:

  • Cross-domain (OR) CORS: Cookies + CORS don't play well across different domains. A token based approach allows you to make AJAX calls to any server, on any domain because you use an HTTP header to transmit the user information
  • Stateless: There is no need to keep a session store, the token is a self-contained entity that conveys all the user information. The rest of the state lives in cookies or local storage on the client side
  • CDN: You can serve all the assets of your app from a CDN and your server side is just the API
  • Decoupling: You are not tied to any particular authentication scheme. The token might be generated anywhere, hence your API can be called from anywhere with a single way of authenticating those calls
  • Mobile ready: When you start working on a native platform cookies are not ideal when consuming a token based approach simplifies this a lot
  • CSRF: Since you are not relying on cookies, you don't need to protect against cross site requests
  • Performance: We are not presenting any hard performance benchmarks here, but a network round trip is likely to take more time than calculating to validate a token and parsing its contents

How to implement Token based Authentication in Web API:

  • Add following using Nuget packages to the Web API project. Microsoft Owin is responsible for regenerating and verifying tokens
    • Microsoft.Owin.Host.SystemWeb
    • Microsoft.Owin.Security.OAuth
    • Microsoft.Owin.Cors
  • Create a new class under App_Start folder and then add following code:
    [assembly: OwinStartup(typeof(WebApisTokenAuth.App_Start.Startup))]
    namespace WebApisTokenAuth.App_Start
    {
    public class Startup
    {
    public void Configuration(IAppBuilder app)
    {
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    var myProvider = new AuthorizationServerProvider();
    OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
    {
        AllowInsecureHttp = true,
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
        Provider = myProvider,
        RefreshTokenProvider = new RefreshTokenProvider()
    };
    app.UseOAuthAuthorizationServer(options);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    HttpConfiguration config = new HttpConfiguration();
    WebApiConfig.Register(config);
    }
    }
    }
    Below is the explanation:

    AuthorizationServerProvider: This class is inherited from OAuthorizationServerProvider and overrides methods of it. ValidateClientAuthentication, GrantResourceOwnerCredentials and GrantRefreshToken are some of the noted methods

    RefreshTokenProvider: This class is inherited from IAuthenticationTokenProvider interface and provides implementation for creating the refresh token and regenerate the new access token, if it expired. CreateAsyn() and ReceiveAsync() are the methods used to achieve this
  • Create API controller and Authorize key word at the top to enforce authorization
    • To provide an authentication/authorization, use 'Authorize' key at the top of the action method or the controller
    • Add it at the top of the controller, if it needs to be forced for the entire controller, if not, use it at the Action level

With this I am concluding the illustration. Feel free to share your feedback. Happy Programming !!!

Forms and Windows Based Authentication

Forms Authentication

Forms authentication uses an HTML form to send user credentials to the server and is not an internet standard. This authentication is only appropriate when called from a web application, so that the user can interact with the HTML form.

How it works:

  • Client requests a resource that requires authentication and if user is not authenticated, server returns HTTP 302 (Found) and redirects to a login page
  • User enters credentials and submits the form. Then the server returns another HTTP 302 that redirects back to the original URI along with authentication cookie
  • The client requests the resource again. The request includes the authentication cookie, so the server grants the request
  • HTTP Modules are managed classes whose code is executed in response to a particular event in the request life cycle. Below two modules related to Forms authentication are:
    • FormsAuthenticationModule: authenticates user by inspecting the forms authentication which is typically included in user cookies collection. If no forms authentication is present, the user is anonymous
    • UrlAuthorizationModule: determines whether or not the user is authorized to access the requested URL. This module determines the authority by consulting authorization rules specified in configuration files

Advantages of using Forms Authentication:

  • Easy to implement: built into ASP.NET
  • Uses ASP.NET membership provider, which makes it easy to manage user accounts

Disadvantages of using Forms Authentication:

  • Not a standard HTTP authentication mechanism; uses HTTP cookies instead of the standard Authorization header
  • Requires browser client
  • Credentials are sent as plaintext
  • Vulnerable to cross site request forgery (CSRF); requires anti-CSRF measures
  • Difficult to use form nonbrowser clients. Login requires a browser
  • User credentials are sent in the request
  • Some users disable cookies

How to Implement: Forms Authentication can be implemented as below:

  • Enabling Forms Authentication: The application's authentication configuration is specified through the element in web.config and will have Windows, Forms, Passport and None and below is the syntax in web.config to use Forms authentication:
    <configuration>
    <system.web>
    <authentication mode="Forms" />
    </system.web>
    </configuration>

Windows Authentication

Windows authentication enables users to log in with their Windows credentials, using Kerberos or NTLM. Client sends credentials in the Authorization header. This type of authentication works best for intranet environments

Advantages of using Windows Authentication:

  • Built into IIS
  • User credentials will not be sent as part of request
  • No need to provide user credentials in case if the client machine belongs to the domain

Disadvantages of using Windows Authentication:

  • Not suitable for Internet applications
  • Either Kerberos or NTLM support is required in the client
  • Client must be added to the Domain's Active Directory

How to Implement: Windows Authentication can be implemented as below:

  • Enabling Windows Authentication: The application's authentication configuration is specified through the element in web.config and will have Windows, Forms, Passport and None and below is the syntax in web.config to use Forms authentication:
    <configuration>
    <system.web>
    <authentication mode="windows" />
    </system.web>
    </configuration>

With this I am concluding the illustration. Feel free to share your feedback. Happy Programming !!!

AngularJS

Coming Soon ...

Model First Approach

This is another way besides Code First and Database First approaches to create and work with your models using Entity Framework. If supports

  • "Draw" your model and lets workflow generate the database and POCO classes
  • Model is stored in EDMX and can be viewed and edited using EF Designer
  • The classes that you interact with in your application are generated from the EDMX file



Model First approach is recommended when:
  • Is useful when starting a new project where the database doesn't event exist
  • One don't want to write neither code not SQL
  • Draw the Model using designer and workflow will generate everything you need
Advantages
  • Will be able to create the Database schema and the class diagram as a whole using the EF designer, which is great when the data structure is big
  • Whenever there is a Database change, the Model can be updated without data loss
Disadvantages
  • The diagram driven, autogenerated SQL scripts can lead to data loss in case of updates. So, as a workaround the changes need to be manual instead.
  • Dealing with the diagram can be tricky, especially if we want to have control over the Model classes
Steps to implement Model First approach
  • Create a new ASP.NET MVC or Web API project
  • Using Manage Nuget Packages option install latest Entity Framework
  • Add New ADO.NET Entity Data Model item to the project by selecting "Empty EF Designer Model" option
  • Right click and add New Entity on EDMX designer
  • Once all required Entities are created, Database can be generated by right clicking and selecting "Generate Database from Model" option
  • Now, generate T4 templates using "Add Code Generation Item" from right clicking on EDMX designer

Database First Approach

This is another way of creating model classes and work with them. In this workflow model, it supports:

  • Creates Model / POCO objects from an existing database and these will become the link between the database and controller(s)
  • It uses the model/database sync, code generation, in the same way as we used in the Model First approach
  • This is an alternative approach provided by Entity Framework besides Code First and Model First approaches









Database First approach is recommended when:
  • Working with stable databases schemas
  • Changes to database and models are incremental
  • When you have a database designed separately by DBAs or if you have existing database
Advantages
  • Useful when the database is already existing
  • Simple to create the data model using existing database objects
  • Mapping and creation of keys and relationships are automatically handled by EF and no need to write any code
  • Usually preferred for intense data and large applications
  • Easy to avoid data loss on changes as you wlll work from database perspective
  • Query performance and better integrated with Stored Procedures and Functions
Disadvantages
  • Giant pile of auto generated code when working with an huge database to generate EDMX
  • Always needs to extend the auto generated classes to extend the functionality
  • Creating associations, foreign keys, constraints etc. from the database can be more difficult
  • Not easy to sync database changes made locally
  • Sometimes handling edmx with version controlling is challenge
  • Database deployment is a painful process
  • Going forward EF will not support EDMX based modeling
Steps to implement Database First approach
  • Create a new ASP.NET MVC or Web API project
  • Using Manage Nuget Packages option install latest Entity Framework
  • Update web.config with connection string
  • Generate Model(s) by
    • Data -> ADO.NET Entity Data Model
    • Then pick "EF Designer" from Database
    • Pick newly created context from web.config as new context class name
    • Select needed SQL objects like Tables, Views and Stored Procedures
    • Once clicking on Ok, Models and .edmx will be generated after theses steps
  • Updating .edmx can be done by
    • Make required changes using SSMS
    • From .edmx, right click and pick "Update Model from Database" option
  • Fluent API will go hand to hand to create relationships like one-to-zeroorone, one-to-many and many-to-many etc.

Code First Approach

This is one of the three approaches what Entity Framework provides to create an entity model and work with it. In this model of work flow, it supports :

  • This approach targets a database which doesn't exist yet and Code First will create it
  • Can be used against a blank database, means database exists but no tables are in place to use within the database
  • Additional needed configurations can be performed either using Data Annotations, Properties or with the help of Fluent API








Code First approach is recommended when:
  • Model classes contain logic and contain non-standard structures
  • Model is divided between many assemblies that are not all known at design time
  • Databases are short lived and can often change
  • When one wants to be able to write and quickly and easily run integration tests on LocalDB
  • If you rather see the model and the mappings in a single place instead of going over diagrams and mapping windows
Advantages:
  • One common syntax like LINQ for all object queries whether it is database or not
  • Pretty fast if used as intended and easy to implement Separation of Concerns
  • Less coding required to accomplish complex tasks
  • It's fast and straight forward using LINQ objects for all CRUD operations
  • Easy to map business objects
  • Keeps good performance when you work with a small / middle domain model
Disadvantages:
  • You have to think in a non traditional way of handling data, not available for every database
  • If there is any schema change in database, you have to update the schema and solution as well
  • It's limited when you work with a huge domain model
Steps to implement Code First approach
  • Create a new ASP.NET MVC or Web API project
  • Using "Manage Nuget Packages" option install latest Entity Framework
  • Update web.config with connection string
    <connectionStrings>
    <add name="CodeFirstApproachContext" connectionString="data source=DESKTOP-BSV3G59\SQLEXPRESS;Initial Catalog=CodeFirstApproach; Integrated Security=SSPI;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
    </connectionStrings>
  • Create new Context class (best practice is to have the same as connection string name) by deriving it from DbContext. This will contain the OnModelCreating override along with DbSet<> definitions
  • Start adding your POCO objects to Model folder as you need
  • Launch Package Manager Console and execute below commands in the same order to generate the required files
    • enable-migrations This will create Migrations folder and Configuration.cs file with settings
    • add-migration "Name of the migration" This will create the migration file of provided name with changes to run
    • update-database -verbose This command will run the migrations created as part of above command to update the database with identified changes
  • After this step, we can check the database by launching SSMS to see the created tables as updated by update-database command above
  • All DbSet<> will be created and can be accessed using context object
  • From now on, any kind of changes to the POCO objects needs to be taken care by using add-migration and update-database -verbose commands

Object Oriented Programming

Object Oriented Programming is a methodology to design a program using classes and objects. It simplifies the software development and maintenance with the help of:

  • Object: Any Entity that has state and behavior is known as an Object which can be physical and logical
  • Class: Collection of Objects is called class. It is a logical entity
  • Inheritance: This allows one to define a class in terms of another class, which makes it easier to create and maintain applications. This provides code reusability and is also be used to achieve runtime polymorphism.

    Terminology used for Inheritance:
    • Base Class: The class whose features are inherited is knows as base class / super class / parent class
    • Sub Class: The class that inherits the base/super/parent class is known as subclass. This can add it's own fields and methods on top of base class
    • Reusability: When we want to create a new class and if there is a class already existing with some methods, we can derive that as a new class which is called reusability
    Syntax:
    The symbol used for Inheritance is :

    public class derived-class : base-class {
    // code goes here . . .
    }
    Types of Inheritance:
    • Single Inheritance: In this sub classes will inherit features, methods and fields from one super class
    • Multilevel Inheritance: In this, a derived class will inherit from a base class as well as the derived class will also be a base class for other classes
    • Hierarchical Inheritance: In this, once class will be served as super class for more than one sub class
    • Multiple Inheritance: The derived class can be derived from more than one base class. Remember, C# does not support multiple inheritance at class level, but will support multiple inheritance at interface level
    • Hybrid Inheritance: This is a mix of two or more inheritance types. This also, can be achieved in C# using interfaces and not with classes
  • Polymorphism: Means having many forms. In OOP paradigm, this is often referred as, "One interface, multiple functions"

    Types of Polymorphism:
    • Static Polymorphism: The mechanism of linking a function with an object during compile time is called static polymorphism which is also called as early binding. Below are the techniques used to implement static polymorphism in C#:
      • Function Overloading: We can have multiple definitions for the same function in the same scope and must differ from each other by the types or the number of arguments. And, cannot be differentiated by the return type
      • Operator Overloading: Most of the built-in C# operators can be overloaded. These are the functions with special names with Operator keyword followed by the symbol for the operator being defined. These also have a return type and a parameter list
    • Dynamic Polymorphism: This is implemented in C# by Abstract classes and Virtual Functions
      • Abstract classes provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. These classes contain abstract methods which are implemented by the derived class. You cannot create an instance of an abstract class. You cannot declare an abstract method outside an abstract class. And, when a class is declared as Sealted, then, it cannot be inherited and abstract classes cannot be sealed
      • You use virtual functions defined when you want the function to be implemented differently as part of inherited classes. This will help deciding the function behavior at runtime instead of compile time.
  • Abstraction: Hiding internal details and showing functionality is known as Abstraction. Using Abstract class and Interfaces one can achieve Abstraction in C#. An abstract class is never intended to be instantiated directly. And, these classes are typically used to deifne a base class in the class hierarchy. This class must contain atleast one abstract method which is marked by the keyword abstract in the class definition. The keyword abstract modifier indicates the incomplete implementation.

    Points to remember:
    • Abstraction is used at the time of Inheritance
    • One must use the override keyword before the method which is declared as abstract in child class, the abstract class is used to inherit in the child class
    • An abstract class cannot be inherited by structures
    • Contains constructors and destructors
    • Can implement methods with non-abstract mehtods
    • Cannot support multiple inheritance
    • Cannot be static
  • Encapsulation: Wrapping Data and Code together into a single unit is called as Encapsulation. Technically, the variables or data of a class are hidden from any other class and this can be shared or accessed only through access modifiers. As the data in a class is hidden for other classes, this is also called as data hiding

    Advantages:
    • Data Hiding: User will have no idea about the inner implementation of a class. He only knows the we are passing values to accessors and variables are getting initialized to that value
    • Increased Flexibility: The variables of the class are either read-only or write-only depending on requirement. By using Get and Set accessor this can be achieved
    • Reusability: This also improves reusability to change the behavior
    • Unit Testing: This is easy to unit test code

Advantages

  • Simple: The programmes written with OOP are really easy to understand. Since everything is treated as Objects, one can model a real-world concepts using OOP
  • Modular: Since the parallel development of classes is possible in OOP concept, it results in the quick development of the complete programmes. Each object forms a separate entity whose internal workings are decoupled from other parts of the system
  • Secured: It is a secured development technique since data is hidden and can't be accessed by external functions
  • Extensible: Adding new features or responding to changes in operating environments can be solved by introducing few new object and modifying existing ones
  • Maintainable: Programmes written using OOP technique are marginally easier to test, manage as well as maintain
  • Reusable: This approach offers the reusability of classes. We can reuse the classes that are already created without writing them again and again

DisAdvantages

  • Sometimes the relation between classes become artificial
  • Designing a program using OOP concepts is little bit tricky
  • One should have a proper planning before designing a program using OOP approach
  • As everything is treated as objects in OOP, the programmers need proper design, programming and thinking skills in terms of objects
  • The size of programmes developed with OOP is larger than the procedural approach
  • Since large in size, more instructions need to be executed, which results in slower execution of programmes