Monday, July 16, 2018

Creating First Application using Angular2

Below you will find how to configure the solution architecture for Angular2 using Visual Studio Code editor and system.config.js to load modules using TypeScript compiler.

Below are the prerequisites to create Angular2 Application:

Use below instructions/steps to start creating your first Angular2 application:

  • Create new folder in your drive where you want to keep the code base
  • Launch Visual Studio Code editor and select the created folder using File -> Open -> Select Folder
  • Create new file and name it as package.json under the project folder and paste below code. This file contains all the dependencies of the project.
  • {
      "name": "angular2-demo-visual-studio",
      "version": "1.0.0",
      "description": "QuickStart package.json from the documentation, supplemented with testing support",
      "scripts": {
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" ",
        "docker-build": "docker build -t ng2-quickstart .",
        "docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
        "pree2e": "npm run webdriver:update",
        "e2e": "tsc && concurrently \"http-server -s\" \"protractor protractor.config.js\" --kill-others --success first",
        "lint": "tslint ./app/**/*.ts -t verbose",
        "lite": "lite-server",
        "postinstall": "typings install",
        "test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
        "test-once": "tsc && karma start karma.conf.js --single-run",
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "typings": "typings",
        "webdriver:update": "webdriver-manager update"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "@angular/common": "~2.0.1",
        "@angular/compiler": "~2.0.1",
        "@angular/core": "~2.0.1",
        "@angular/forms": "~2.0.1",
        "@angular/http": "~2.0.1",
        "@angular/platform-browser": "~2.0.1",
        "@angular/platform-browser-dynamic": "~2.0.1",
        "@angular/router": "~3.0.1",
        "@angular/upgrade": "~2.0.1",
        "angular-in-memory-web-api": "~0.1.1",
        "bootstrap": "^3.3.7",
        "systemjs": "0.19.39",
        "core-js": "^2.4.1",
        "reflect-metadata": "^0.1.8",
        "rxjs": "5.0.0-beta.12",
        "zone.js": "^0.6.25"
      },
      "devDependencies": {
        "concurrently": "^3.0.0",
        "lite-server": "^2.2.2",
        "typescript": "^2.0.3",
        "typings": "^1.4.0",
        "canonical-path": "0.0.2",
        "http-server": "^0.9.0",
        "tslint": "^3.15.1",
        "lodash": "^4.16.2",
        "jasmine-core": "~2.5.2",
        "karma": "^1.3.0",
        "karma-chrome-launcher": "^2.0.0",
        "karma-cli": "^1.0.1",
        "karma-htmlfile-reporter": "^0.3.4",
        "karma-jasmine": "^1.0.2",
        "karma-jasmine-html-reporter": "^0.2.2",
        "protractor": "^3.3.0",
        "rimraf": "^2.5.4"
      },
      "repository": {}
    }
  • Create another file and name it as tsconfig.json and paste below code. This file is used to compile TypeScript code.
  • {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": true,
        "suppressImplicitAnyIndexErrors": true,
        "typeRoots": [
        "node_modules/@types"
        ]
      },
      "compileOnSave": true
    }
  • Create another file and name it as typings.json and paste below code. This file contains all TypeScript compiler libraries.
  • {
      "globalDependencies": {
        "angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
        "core-js": "registry:dt/core-js#0.0.0+20160725163759",
        "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
        "node": "registry:dt/node#6.0.0+20160831021119",
        "selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
      }
    }
  • Launch Integrated Command Terminal using View tab to install dependencies. Use npm install command to start installing the dependencies.
  • Create new folder and name it as app which contains all application related folders and files in it.
  • Create another new file and name it as systemjs.config.js to load modules and paste below code in it:
  • /**
    * System configuration for Angular samples
    * Adjust as necessary for your application needs.
    */
    (function(global) {
    System.config({
    paths: {
    // paths serve as alias
    'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
    // our app is within the app folder
    app: 'app',
    // angular bundles
    '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
    '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
    '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
    '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
    '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
    // other libraries
    'rxjs': 'npm:rxjs',
    'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
    app: {
    main: './main.js',
    defaultExtension: 'js'
    },
    rxjs: {
    defaultExtension: 'js'
    },
    'angular-in-memory-web-api': {
    main: './index.js',
    defaultExtension: 'js'
    }
    }
    });
    })(this);
  • Now, start creating the required files under app folder. Click on app folder and create new file called app.component.ts and paste below code in it.
  • import { Component } from '@angular/core';

    @Component ({
       selector: 'my-app',
         templateUrl:'app/views/app.component.html'
    })

    export class AppComponent {
         appTitle: string = 'Welcome';
    }
  • Create another new file called app.module.ts and paste below code:
  • import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    import { HttpModule } from '@angular/http';

    @NgModule({
         imports: [BrowserModule, HttpModule],
          declarations: [AppComponent],
          bootstrap: [AppComponent]
    })

    export class AppModule { }
  • Now, create new file called main.ts and paste below code. This file is used to register all your modules.
  • import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
    import { AppModule } from './app.module';
    const platform = platformBrowserDynamic();
    platform.bootstrapModule(AppModule);
  • Now, last but not least, create new html file called Index.html under main folder of the application and paste below code
  • <html>
       <head>
          <title>My First Angular 2 Practice using Visual Studio 2015</title>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <!--<link rel="stylesheet" href="styles.css">-->

          <!-- 1. Load libraries -->
          <!-- Polyfill(s) for older browsers -->
          <script src="node_modules/core-js/client/shim.min.js"></script>
          <script src="node_modules/zone.js/dist/zone.js"></script>
          <script src="node_modules/systemjs/dist/system.src.js"></script>

          <!-- 2. Configure SystemJS -->
          <script src="systemjs.config.js"></script>
          <script>
             System.import('app').catch(function(err){ console.error(err); });
          </script>
       </head>

       <!-- 3. Display the application -->
       <body>
          <my-app></my-app>
       </body>
    </html>

You are good to run your first Anguar2 application. Using Integrated Command Terminal run npm start command to launch and run the above created application, which looks as below in browser:

Happy Programming !!!

Tuesday, July 10, 2018

Angular2: Environment, Features and Components

Environment: The key components which are needed for Angular 2 are:

NPM - Node Package Manager: Which is used to work with open source repositories. This is used to download the dependencies and attach them to the project as Angular 2 as a framework has dependencies on other components.

Git: Can be used to get the sample application from GitHub for Angular.

Editor: Many editors can be used to develop Angular applications such as Visual Studio Code, Visual Studio and WebStorm.

Different ways to get started with Angular are:
  • One way is to do everything from scratch which is the most difficult and not the preferred way due to the number of dependencies.
  • Another way is to use the quick start at Angular GitHub. This contains the necessary code to get started. This is normally what is opted by all developers. GitHub Location to Download
  • The final way is to use Angular CLI
Features: Following are the key features of Angular 2:
  • Components: These will help to build the applications into many modules. Components are over Controllers from AngularJS.
  • TypeScript: This is a superset of JavaScript and is the basis for Angular 2
  • Services: Services are set of code which can be shared by different components of an application. As an example, if you had a data component that picked data from a database could have it as a shared service that could be used across multiple applications

In addition, Angular 2 has better event handling capabilities, powerful templates and better support for module devices.

Components: Below are components of Angular 2:
  • Modules: help separate the functionality of application into logical pieces of code. Usually each piece of code or module is designed to perform a single task. If you are using Visual Studio Code, app.module.ts file under app folder contains the root module class.
  • Component: can be used to bring the modules together, and are logical pieces of code in an angular application. If you are using Visual Studio Code, App.component.ts file in app folder contains this file
  • Template: used to render the view for the application. This contains the HTML that needs to be rendered in the application. This part also includes the binding and directives
  • Metadata: is used to decorate a class so that it can configure the expected behavior of the class and consists of Annotations and Parameters as parts and resides as part of app.component.ts file
  • Services: used to create components which can be shared across the application
Setting up the Environment:
If you selected Visual Studio Code as your Editor:
If you selected Visual Studio 2015 as your Editor:
Verify the Installed Versions
  • Open command prompt and use node -v to get Node.js version
  • Open command prompt and use npm -v to get NPM version
  • Launch Visual Studio -> Help Menu -> About Microsoft Visual Studio to get the Visual Studio version
  • Launch Visual Studio -> Help Menu -> About Microsoft Visual Studio to get the TypeScript version

Once these are ready, we are good to START creating our FIRST Angular 2 Application.

Happy Programming !!!

Monday, July 9, 2018

Authetication & Authorization

This topic illustrates different ways of implementing Authentication and Authorization using ASP.NET, MVC and WebApi

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 ...