Showing posts with label WEB. Show all posts
Showing posts with label WEB. Show all posts

Tuesday, April 24, 2018

Trinity of Web: HTML + CSS + JavaScript



At the heart of modern web applications there lays 3 main components which helps/guides users to do shopping on Amazon web site, purchase air tickets from Delta Airlines, connect friends worldwide through Facebook, transfer money from your account to a friend via Bank of America and many other services to better/improve the standard of living of humans.
Let’s briefly go through each component, understand what it means and what it does:

HTML

Hyper Text Markup Language, here markup means marking a word bold or italic or underline or make paragraph by markups like
, PS, HTML is the product of printing technology. So that’s where the word markup came from. In general HTML helps to structures the data or holder of the data.  So if user wants to see their data structured then they should format their data according to html tags/elements.

CSS

Cascading Style Sheets, it’s the styling language used to do designing/presentation/formatting of structured data aka HTML tags/elements. In simple words, via CSS we can say what is the color of font/ size, how and where to position the images, what type of fonts, size of the grid/table etc. User must follow the rules of CSS styling language.

JavaScript

Plays behavioral role or it interacts with the user, for ex: Alerting users through message boxes, or when user clicks on submit button, JavaScript validates user has entered all the required/mandatory field before submitting data to sever, etc. Through JS user can request data from server for ex: their checking account balances or transaction data.

Each of the above components are worth of a book or more. But in general it is simple, Structure + Present + Behavior combined all these three makes the web working and helps human to improve their standard of living or simplify.

A very simple/real working example of all of the above components is as follows:
<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Simple web app</title>
    <style>
        button
        {
            color: white;
            background-color: lightblue;             
        }

    </style>
    <script type="text/javascript">

        function Hello() {
            alert("Thanks for clicking me!");
        }

    </script>
</head>

<body>
    <div>
        <button onclick="Hello();">Please Click On Me!</button>
    </div>
</body>
</html>

You can copy and paste it on a notepad/textpad and open it from a browser, then you should see a screen like below (I opened it through Google chrome)


Sunday, July 23, 2017

How to intercept HTTP request? asp.net core, IHTTPModule, middleware

Asp.net core is a brand new, open source and cross platform framework for building modern internet applications. Unlike its predecessor Asp.net core is lightweight, robust, fast (Kestrel Web server), and cloud ready.

Asp.net core is designed to integrate seamlessly with varieties of client side frameworks like AngularJS, ReactJS, KnockoutJS

Modern internet applications communication language is HTTP. So you will came across many scenarios to intercept client’s HTTP request and process it. I will explain a real scenario, “As part of application authentication, you have to make sure user\company employee must be logged into their corporate network/global login before accessing application.”

In Asp.net core Middleware’s replaced IHTTPModule and IHTTPHandler.  Middleware is an application pipeline to handle request and response .

I will quickly walk through you the code snippets:
         First create two class as below
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication5.Middleware
{
    public class CustomMiddleware
    {
        private readonly RequestDelegate _next;

        public CustomMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
         
            string companyAuthCookie = ApiHelper.GetConfigValue("companyAuthCookie");
            bool securityEnabled = bool.Parse(ApiHelper.GetConfigValue("SecurityEnabled"));

            if (securityEnabled)
            {
                var header = context.Request.Headers;
                var cookies = context.Request.Cookies;

                if (cookies.ContainsKey(companyAuthCookie))
                {
                    //allow other middle to process http request
                    await _next.Invoke(context);
                }
                else
                {
                    //short circuit or terminate http process request because user haven't logged in
                    context.Response.Redirect(ApiHelper.GetConfigValue("RedirectUrl"));
                }
            }
            else
            {
                await _next.Invoke(context);
            }
        }
    }

    public static class CustomMiddlewareExtensions
    {
        public static IApplicationBuilder UseCSPMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CustomMiddleware>();
        }
    }
}

Then goto Startup class (Startup.cs)

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

               //in asp.net core order is important. Make sure you call it in early stage
            app.UseCSPMiddleware();

            app.UseMvc();
        }

That’s it, you have created code to intercept http request and process it inside asp.net core.

Reference: 

Thursday, April 13, 2017

Asp.net Core MVC CORS preflight issue REST api

Browser -> CORS -> IIS -> Kestrel Asp.net Core MVC REST apis

Project:
Silverlight migration project into HTML5/AngularJS/Asp.net Core MVC.

Problem:
CORS preflight (http options) request was throwing 403 forbidden error.

Story & Solution:

I did hosted Asp.net core REST apis on IIS, initially UI\AngularJS developers were consuming basic GET api's everything was going smooth.
Next, when they tried to consume my http POST apis, panic button pressed its not working.

Unlike WFC, xml web services, web apis, Asp.Net Core MVC has brand new web server called 'Kestrel' which is faster and modern compared to IIS. But Kestrel is not matured enough to put behind internet so we have to do reverse proxy using IIS, basically IIS forwards http calls to kestrel and vice versa. Story doesn't end their to make complicated, when angularjs or client makes calls from modern browsers, it will make a preflight call to web server to make sure request service is available and client has access, this is for security purpose according W3C CORS standard. So browser make a preflight http OPTIONS request, but most web server doesn't enable or accept http OPTIONS, PUT, Delete requests, admin disables it by default Then developer have to scratch his head and trace where its going wrong.

Solutions:

So, when you stuck, pls go through the following areas, which might help you to solve the issue.

a) Enable http log at IIS level, go through the logs.

b) Enable logging at asp.net core mvc api.

c) Use Fiddler or REST api client like postman(beware unlike browser postman doesn't make preflight request, it works here but from browser it fails)

d) In web config allow required verbs

e) Verify url scan config.

f) Verify and make sure all the required configs are enabled system32\inetserv\config applicationhost root config file for IIS.


Pls make sure changes you do must be compliance towards company cyber security policies.

PS: above tips works well other web servers; apache, nginx ...

Tuesday, March 28, 2017

What is HTTP2, HTTP/2, SPDY?


History:

HTTP – hypertext transfer protocol. It’s an Application protocol to exchange hypertext or hypermedia over World Wide Web. Hyper text\media means, a HTML page is nothing but a text document contains links to other documents or media. So user can open a web page and traverse to other pages and come back.
The term hypertext was coined by Ted Nelson in 1965 for his xanadu project.
But actual credit goes to Tim Berners Lee and his team at CERN. In 1989, He proposed a system to track tons information\data created by LHC. Basically, Tim wanted to create a system to link documents and access over network.

Evolution of HTTP:

HTTP/0.9

1989. Simplest, it just had a single method GET, no headers. It supported just to fetch text documents, no images.

HTTP/1.0

1995. By this time http proven its potential. RFC 1945 introduced, headers, response codes, errors …

HTTP/1.1

1996 to 2010 (approx.) 1.1 has six RFCs, addressing issues of message, cache, pipeline, semantics …

SPDY

2009, google proposed alternative to HTTP they called it SPDY. It contains features like multiplexing, framing, header compression, etc.

HTTP/2

May 14, 2015. SPDY was the driving force of HTTP/2. RFC 7540 made official of HTTP/2
Data compression of headers, Multiplex, Pipelining of requests, Server push, Priority requests…

Why HTTP2?


To know answer for question why http2, we have to understand evolution of http. It started with simple GET, serving simple html/text pages to present serving a text file to ultra hd video over internet. When a user types and enter a url on a browser, behind the scene a series of action will be performed before user sees what they want. Briefly here is what happens: Resolve Hostname (DNS), Open TCP connection, Handshake, Get Data …
In simple word answer to above question is “Latency”. How much time it takes to get data from server to client. Previous versions of http were struggling to handle modern, high volume traffics. HTTP/2 will address drawbacks of earlier versions. So HTTP/2 enhances existing http features and speed up process to get by implementing clever techniques.

Most of the modern browsers and web servers support http/2 features. Say thanks to google and IETF.





Sunday, February 26, 2017

Hello world asp.net core mvc (RESTful service) (Create Service,Build,Host,Test)

Here is very easy step by step process to create a complete(Create Service,Build,Host,Test) simple \ hello world equivalent REST ful service using asp.net core mvc.

Audience: Beginners\Intermediate

Environment :
VS 2015 SP 3
.Net core sdk (https://www.microsoft.com/net/download/core)
Windows 7
IIS 6.1


 Open new project, select asp.net core, give a name to project


 Select Web Api( this actually means RESTful service)


Next you will see solution like this


Click on valuecontroller.cs. You will see code like below, this is the default code you will see. We will modify slightly REST services in next screen shot.



Basically controller is the module which receives the client\web browser http request and processes it. Internally Routing middleware is the responsible for routing call to this valuescontroller and all http requests. Notice attribute routing [Route("api/[controller]")], so client have to invoke like www.name.com/../api/values . Next is [HTTPGet], like HTTP verb, which returns a collection or single entity
Click on Program.cs, you will see code like below. asp.net core has built up from scratch so it has new fast web server, its built into asp.net core, and its called Kestrel (async web server, platform independent, written using c libraries). Notice, iisintegration that is basically reverse proxy. IIS all it does is passes client http request to kestrel and vice versa.

Now lets build it

Select custom

 File system , select the output folder


Open IIS manager, Add new application, enter alias, select app pool.


Create a new app pool, notice its no manage code (its .net core)

 Go to the output folder, make sure iis_iusrs exist or have appropriate rights
That’s it.
Goto your favorite browser, type http://localhost/hellorestful/api/values/1


http://localhost/hellorestful/api/values

Sunday, January 22, 2017

Cryptography in a minute! (how to encrypt\decrypt data of Wired or Wireless)


Cryptography is the art and science of secure communication. “kryptos” is Greek word, which means ‘secret writing’.

Cryptography is not a modern invention nor because of dawn of computers, in fact its almost 3 or 4 thousand years old practice of communicating securely. Kings as part of warfare or strategy were sending messages from one king to another in secret writing so that his\her enemy shouldn’t able to read the messages by capturing the messenger. Secret writing like, write message in hidden ink, substitution cipher (with shift of 3 A will be C, C will F) etc.

Almost all modern encryption\decryption of data, whether it’s WIRED (web, file system, messages) or WIRELESS (cell, sensors) done by three ways:

  •    Symmetric key
  •    Asymmetric key
  •    Mix of Symmetric and Asymmetric keys



Symmetric key cryptography


Symmetric (reflection or mirror) uses a single secret\shared key for both encryption and decryption. In this type of crypto both sender and receiver should know the secret key up front.
Sender encrypts the message using secret key, message transferred over network, Receiver decrypts the message using same secret key used for encryption.




pic courtesy Oracle corp.


The main drawback of shared-key crypto is the difficulty of securing the secret-key, which needed by both sender and receiver, so high chances of leaking the key. It’s called key distribution problem.

Asymmetric key cryptography


Also called public-key or public private key cryptography. Due to the drawbacks of symmetric key, made the way to invention of asymmetric key.
  
Public-key cryptography, proposed by Diffie and Hellman in 1976, is the idea of having two separate keys, a public key for encryption of a message and a secret key for its decryption; a party can privately construct the two keys and then make the encryption key public without thereby revealing the decryption key. Subsequently, anyone can encrypt messages intended for the creator of the keys, but only the creator can decrypt. The first realization of this idea was due to Rivest, Shamir, and Adleman in 1978.

At the heart of RSA – public key crypto is depend upon the properties of the product of two large prime numbers. This algorithm is based on some principles from Number theory, which states that determining the prime factors of a large number is extremely difficult.






pic courtesy Wiki


Differences


Symmetric key
Asymmetric key
Encrypts 256 bits
Encrypts 1024 bits or 2048 bits
The size of ciphered text is less or equal to plain text
The size of ciphered text is heavy
Less computing power
Need lot of computing power
Used : client and server
Used for: digital signature, session key …
DES, AES algorithm
RSA algorithm
Same key for encrypt and decrypt
Public key for encrypt and private key for decrypt



Cryptanalysis is the art and science of breaking the encrypted codes that are created by applying some cryptographic algorithms.