Authentication and Authorization in ASP.NET Web API using Custom Filters

  • Web API is a platform for building RESTful applications on DotNet Framework. 
  • These API’s can be consumed from Console, Windows, Web, Mobile Applications.
  • As Web API is a part of core ASP.NET, it can be created on either MVC applications, or any other web applications.
  • Web API’s uses all the HTTP features like Request and Response headers, caching and so on…
  • Web API’s can return the data in various formats like
    • string format
    • Json format
    • XML format
    • BSON format

Step 1: Create a  ASP.NET Web API application

Open Visual Studio –> File –> New –> Project –> choose template Web –> click on ASP.NET Web Application  and provide name of the application–> choose Web API from the below check boxes –> Click OK

Step 2: Create a Model and inherit GenericIdentity from Security.Principal assembly

File: UserModel.cs


Step 3: Now add a new class for Creating custom filter as MyAuthorization and inherit AuthorizationFilterAttribute and add the following assemblies MyAuthorization class.

File: MyAuthorization.cs


Step 4: Here is your CustomAuthorization Filter MyAutorization


Step 5: Now create an API Controller and add your custom filter. Here I’m adding for only one method for testing you can add it for the entire class or add it globally.

File: Global.asax 

Add the below line in Application_Start( ), this registers our custom Filter for the entire application.

 File: EmployeeAPIController.cs


Step 6: Now create your GUI and on a button click write a server side method. Form this method you can communicate with API. In my case I took a console application.

  1. If you run the web project you will get your local host URL, in my case it was http://localhost:58100/
  2. Here in the authorization Header I have added my username and password in the given format username:password and encoding it to Base64 so that it provides security.
  3. If you don’t pass valid credentials from here, in the method OnAuthorization it should add Unauthorized Response.


Step 7: Create console / windows/ web application to consume the API

Here I’ve created Console application.

File: Program.cs

  • Here HTTPClient is used to consume RESTful API’s.
  • And then creating the Authorization header to pass the username and password in format (username: password).
  • client.GetAsync consumes the API and returns the Result.
  • From the result we can check the Status Code.


Angular 4 Directives – Lesson 3.3

3.2 Attribute Directives

Here directive is just a class with decorator @Directive and this allows us to specify the directive’s selector.

  • Using custom attribute directive we can change the color, back-ground, font-size etc., of the HTML host element by using ElementRef
  • Renderer class is a built-in service that provides an abstraction for UI rendering manipulations.

Let’s create a custom attribute directive “ShowAlert

Step 1: Create a folder and name it as CustomDirective: /src/app/CustomDirective

Step 2: Now create a typescript file to create your own attribute directive under the associated folder created. And then import Directive, ElementRef, HostListener, Renderer from @angular/core library.

Step 3: And provide your selector name, here I’ve named it as ShowAlert, and create a class that make this directive visible to the component i.e.,add export before the class.

File: app.myDirective.ts

Step 4: Now define contructor for FirstAttrDirective class, and define the style and events using renderer.

For setting up styles,

Renderer.setElementStyle(rendererElement:any, styleName: string, styleValue: string)


For creating events,

Renderer.listen(parentElement: any, name: string, callBack: function)

Step 5: Create your component

File: app.component.ts

Step 6: Add component and Directive in the declaration[ ] of the NgModule  i.e., AppModule

Step 7:  Create a main.ts to bootstrap the NgModule

Step 8: Create a HTML file in /src/

File: CustomDirective.html

Refer required scripts shim.min.js, zone.js, system.src.js, system.config.js and refer the main.js from CustomDirective folder

Output: Default color will be blue, on mouseover font size get increased and changes its color to red, on mouseout will change color to blue and decrease its font size.

Tadaaaa.. 🙂

Angular 4 Directives- Lesson 3.2

Hi friends, in the last session we have learned about built-in directives (ngIf, ngFor, ngSwitch). In this session we will learn,

  • Style and Class Directives ( ngClass, ngStyle)


  • It is used to add and remove CSS classes on an HTML element.
  • CSS Classes can be added in several ways
  1. Using string
  2. Using array
  3. Using object
  4. Using Component methods
  • When using ngClass with object, classes will be added and removed based on the Boolean value that returned.
  • If the value of expression istrue then respective CSS class will be added otherwise that CSS class will be removed from HTML element at run time.

Using String: When using string format, class names must be presented between single quotes with in double quotes “‘class1′” and multiple classes can be separated by space.

File: template.html

File: app.component.ts

Adding styles for the respective classes in component

ngClass using array: When using Array format, each ngClass array item (i.e.,class) must be presented in the string format.

Ex: [ngClass] =”[‘class1′,’class2’]”

File: template.html

ngClass using object: When using object, classes will be formatted in the form of object i.e., each class will be of key and value pairs.

Key: css class name

Value: expression that returns Boolean value

In component file add styles for the respective classes

Using Component Methods: Whereas when using component methods, instead declaring styles statically here styles will be dynamically rendered into template by calling component methods.

  • Depending upon the need/requirement we can pass parameters to the component methods and can dynamically get the required styles.

Ex: [ngClass]=”GetStyles( )”

File: template.html

File: app.component.ts

ngStyle: This directive is used to modify the elements / component styles

  • It accepts an object which defines the elements styles.
  • Both kebab case and lower camel case can be used when specifying style properties.
  • Flexible to add and remove style properties.

File: template.html

File: app.component.ts

JSX Expressions

  • Overview of JSX
  • Creating HTML/XML elements/nodes with JSX
  • JSX Attributes / props
  • Comments in JSX
  • Expressions with
    • Arithmetic operators
    • Ternary Operators
    • Comparison Operators
    • Assignment Operators

Overview of JSX

  1. The full-form of JSX is Javascript and XML, e., simply JSX = Javascript + XML/HTML
  2. JSX is a simple syntax with a combination of HTML/XML tags with Javascript
  3. React used JavaScript expressions within curly braces “{ <expression> }”. We can put any type of JavaScript expression in the curly braces inside JSX.
  4. React can perform only one-way binding, to perform two-way binding we need to use React component’s state and props/ Event listeners.
  5. Each React Element is like a real kind of javascript object which can be either stored in a variable or can be used throughout the program.
  6. After coding in JSX pages no need to precompile the code, the JSX file will be automatically compiled and generates JavaScript syntax in the browser if the JSX is written in ES5, but if the JSX is written in ES6 then this should be pre-compiled by either Babel/ Typescript e.,
    1. Babel
      1. Babel is a process that transforms your JSX code (ES6) into Javascript (ES5) which is browser understandable code.
      2. Bable engine abstracts the Reacts ES6 JSX syntax and recreates that into ES5 syntax, for exampleCode written in ES6 syntax

        Now Babel converts it into ES5 syntax as follows
      3. We will install the following dev dependencies:
        1. babel-loader: babel module loader
        2. babel-core: the core transpiler used for transporting ES2015 and JSX code
        3. babel-preset-es2015: ES6/ES2015 support
        4. babel-preset-react: React/JSX support
        5. babel-preset-stage-2: babel preset for some extra features such as destructuring
        6. webpack: for bundling our packages for distribution and managing dependencies
        7. webpack-dev-server: our development server
      4. Babel 6 doesn’t supports the bundle.js to transform the ES6 to ES5, so for that we need to use Babel older version (i.e., 5.8.X) to transform the JSX code to be pre-compiled and generates the javascript and saved into bundle.js (this can be renamed, and this code is rendered int0 browser) by using webpack.config.js.
    2. Typescript
      1. Typescript is a language the can be either written in ES5/ ES6. Typescript has its own compiler tsc(typescript compiler) to pre-compile the ES6 syntax to ES5.
      2. We will install the following dev dependencies:
        1. ts-loader: typescript module loader to build .tsx
        2. typescript: language for programming in react (either in ES5/ ES6 syntax)
        3. webpack: for bundling our packages for distribution and managing dependencies
        4. webpack-dev-server: our development server
        5. This also uses the bundle.js where after compiling will be saved here with ES5 syntax.
        6. React with Typescript will be written in special extension files i.e., .tsx.               Ex: sample.tsx
  7. Within a JSX syntax we can perform both Data-Binding and Event Binding.


Creating HTML/XML Elements/nodes in JSX:

For creating HTML/XML nodes in JSX React provides a pre-defined function.


Where type, props and children are the arguments for function React.createElement( ).

  1. Type (string / React.createClass( ) ):   This is a mandatory argument. Type argument can be a string value (or) it can be a ReactComponent instance.
  1. Props (null / object):   This is an optional argument, where we can pass null (or) an object
  1. Children (null / string / React.createClass( ) / React.createElement( ) ):  This is an optional argument, we can either pass null value (or)  string value (or) React.createElement (or)  React.createClass instance.


ReactDOM.render( ):  For rendering react nodes into DOM, React provides function ReactDOM.render( )  from “react-dom” module.

  1. Rendering in react is also possible on server-side withrenderToString( ).
  2. If a change is made (or) a new child nodes has been added to DOM element, ReactDOM will only update the child nodes which is called Re-Rendering.

Ex: Creating <ul> tag with nested <li> tags


JSX Props: We have already know the syntax for creating custom HTML elements, second parameter props can be passed as an object/null.

  1. Props are nothing but HTML attributes that are passed as name-value pairs.
  2. Props are generally used for passing inputs to the component.
  3. Props can be passed to nodes in a Component (or) directly to the Component.
    1. Props that are used for nodes/elements are called Node Props/Attributes.
    2. Props that are used for Components are called Component Props/Attributes.
  4. Props creating may vary when using Typescript with React (TSX) with Formal React (JSX). When using TSX must define the type of the Props when creating nodes.


Using Typescript with React (TSX)


Comments in JSX:

  • Comments in jsx use //  and /* */



Javascript Expressions:

To make use of Javascript statements with JSX, React provides a syntax using curly braces “{  }”.

Note: Follow the steps for setup ASP.NET MVC application in React Introduction.


Step1: Open your ASP.NET MVC application à  src/expressions.tsx (Creating file expressions.tsx in src )

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.

File: expressions.tsx

File: index.cshtml

File: webpack.config.js

Change the entry point to expressions.tsx


Sum of 2+3 = 5


JSX Expression with Arithmetic Operators:

File: src/expressions.tsx

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.


JSX Expression with Ternary Operators:

Javascript Ternary Operators ( ? : ) returns two expression depending on condition


var a = true;

var result = a == true ?’yes’ : ‘no’;

File: expressions.tsx

Modify the render( ) as follows

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.


JSX Expression with Comparison Operators

Comparison operators are used to compare any two values / variables

List of the comparison operators



JSX Expression with Assignment Operators:

Assignment operators just assigns the value to a variable.



Complete Example

Note: Run webpack.config.js , because unless it is running in the background the changes which we have done will not be reflected in the bundle.js. So make sure that while making any changes in .tsx files, webpack.config.js is running in the background.