Check cross site scripting XSS

 When we develop API we need to keep in mind about security purpose of API which must be protected from attackers .So to protect API from  attacker  we need data to be filtered i.e attacker can't insert any  vulnerable data from outside web.

Here we have a name i.e Cross-site scripting or XSS

Cross-site scripting is a type of security vulnerability that can be found in some web applications. 
XSS attacks enable attackers to insert client-side scripts into web pages viewed by other users. 

A cross-site scripting vulnerability may be used by attackers to  get access controls and get information  like username, password or any important Files.

Lets see How attacker inject  script from client side or from other platform through API.

<script>/*+anycode*/</script>
<img src=1 onerror='/* anycode */'>
 
Types of XSS attack

Reflected XSS:- In this the malicious script comes from the current HTTP request.

Stored XSS:- In this the malicious script comes from the website's database.

DOM-based XSS:- In this the vulnerability exists in client-side code rather than server-side code.


Reflected XSS

Lets see how can we check any input has malicious script in API > Controller > method

UserInput is pass through if Condition and this data sent to check whether the data provided by user is malicious .If yes it return with error. 

If data provided by user is not malicious it will be processed and inserted to database.

CheckScript checkScript = new CheckScript();

if (!checkScript.IsScript(UserInput))
{
    return "Invalid Text!!";
}


CheckScript.cs  is my class 

public class CheckScript
{
public bool IsScript(string data)
{
    if (string.IsNullOrEmpty(data))
        return true;

    var pattren = new StringBuilder();
    //Checks any js events i.e. onKeyUp(), onBlur(), alerts and custom js functions etc.            
    pattren.Append(@"((alert|on\w+|function\s+\w+)\s*\(\s*(['+\d\w](,?\s*['+\d\w]*)*)*\s*\))");
    //Checks any html tags i.e. <script, <embed, <object etc.
    pattren.Append(@"|(<(script|iframe|embed|frame|frameset|object|img|applet|body|html|style|layer|link|ilayer|meta|bgsound))");
    return !Regex.IsMatch(System.Web.HttpUtility.UrlDecode(data), pattren.ToString(), RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
}

We can also validate input from Client Side to protect malicious attack. Even two or three special characters are responsible for malicious attach ie. <,>,/$ etc

This must be restricted to be input from client side 


Basic Rules to Prevent XSS attack

1. Filter input on arrival.

Filteration of data  is most important step to be work on for prevention of xss attack.

2. Encode data on output.

Data must be in Encoded State so that attacher cann't guess the actual output condition.

Note:-Don't use Base64 for encoding
 
3. Use appropriate response headers.

Don't use HTML ,JvaScript in HTTP response.must use Content-Type and X-Content-Type-Options 

4. Content Security Policy.

 We must  use Content Security Policy (CSP)








How to get camelCase/pascal JSON serialized from controller (API)

How to Get JSON in Camel Case from Contoller as Result. 

First of all we need to know what is difference between Camel and Pascal case. 
Pascal case requires the first letter to be in uppercase  while camel case does not.  

Lets see the Problem I faced in my Project.Below Is my Class where UserName and Password are two objects that want to be return  from controller.

ASP.NET Core uses a camelCase formatter by default so the response you will get will be in 
camel case.

Sometime we need to use the result (response) directly on UI side  without any change in Object we need result in Pascal case thats why the issue to be resolve below.

My Class


public class MyClass
{
    public string UserName { get; set; }
    public string Password { get; set; }
}


The Result I get is Like below that is in camel case

{
  "username": "Ram",
  "password": "1234"
}


But I want result to be  same as object Name ( Pascal) i.e '"UserName" and "Password".


Configure JSON Serialization in ASP.NET Core 3 and Later

So In Startup I have used


services.AddControllers()
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});



After using above code Jsonserializer I found desire result by controller as mentioned below.

{
  "UserName": "Ram",
  "Password": "1234"
}


 Configure JSON Serialization in ASP.NET Core 2
  
using Newtonsoft.Json.Serialization;


services
.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddJsonOptions(options =>
    options.SerializerSettings.ContractResolver = new DefaultContractResolver());




Can't bind to 'ngModel' since it isn't a known property of 'input'.

Can't bind to 'ngModal' since it isn't a known property of 'input'.

In angular we will get such error in console. when ever we start binding and data in ngModal in html with angular component we face this error message.

To resolve this error fist we have to know what is NgModel and what is its use

The Angular uses the ngModel directive to achieve the two-way binding on HTML Form elements. It binds to a form element like input , select , selectarea . etc.

So it is two way binding Process.

Basically ngModel is part of FormModule that must be imported in your  app.module.ts

lets check why this error occurs


My  app.module.ts before error

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

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

export class AppModule { }


In angular  we have  app.module.ts file which deals with component. we have to check in app module.ts that have no Formmodule imported

Now when i imported FormModule in app.module.ts

so its look like

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';  <<<<imported here
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
FormsModule <<added
  ],
  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }


or 
import { FormsModule } from '@angular/forms';

and add

@NgModule({
  imports: [
     FormsModule
  ],
})

Try above hope this will resolve error in your component.

                                                      Thanks

How to Use Loop In PgreSQL

    Basic Example to Check loop in Pgresql 
    
     Example 1


do $$
begin
   for cnt in 1..10 loop
    raise notice 'cnt: %', cnt;
   end loop;
end; $$

The Do command will not return  rows. we have to use NOTICES or RAISE other messages with language plpgsql .
Result Comes on executing above Query  
NOTICE:  cnt: 2
NOTICE:  cnt: 3
NOTICE:  cnt: 4
NOTICE:  cnt: 5
NOTICE:  cnt: 6
NOTICE:  cnt: 7
NOTICE:  cnt: 8
NOTICE:  cnt: 9
NOTICE:  cnt: 10
DO

The following code uses the for loop statement to iterate over ten numbers from 10 to 1 and display each of them in each iteration:
Now We can use loop in Function also to get desired result
Example 2
Create table TblPriorityGraph (
  priorityID serial primary key
  ,priorityName varchar(8),
  Counttotal int,
  yearcurrent int,
  MinYear int,
  MaxYear int
 
  )

 Below we will select  record from other table TblTaskTracking 
 any column from table will be selected in ""
 and table name will also be selected in ""  


CREATE OR REPLACE FUNCTION public.fn_setprioritycountforgraph()
    RETURNS TABLE(priorityid integer, priorityname text, counttotal integer, yearcurrent integer, minyear integer, maxyear integer)
    LANGUAGE 'plpgsql'
 

AS $BODY$
  DECLARE L_Counter int:=( SELECT  Extract(year from Min ("DateTaskAssigned")) AS maxyear FROM "TblTaskTracking");      
  DECLARE L_CloseCounter int:=( SELECT  Extract(year from MAX ("DateTaskAssigned")) AS maxyear FROM "TblTaskTracking");      
  DECLARE   L_MinYear int:=L_Counter;      
  DECLARE L_MaxYear int:=L_CloseCounter;  
   BEGIN  
WHILE ( L_Counter <= L_CloseCounter)   loop  
insert into TblPriorityGraph (priorityID,priorityName,Counttotal,yearcurrent,MinYear,MaxYear)      
    select "PriorityID","Priority",count(*),L_Counter,L_MinYear,L_MaxYear
  from "TblTaskTracking" where "PriorityID"=1      
 and Extract( year from "DateTaskAssigned")=L_Counter  and "IsActive"='Y'    
 group by  "PriorityID","Priority";  
 
  L_Counter  := L_Counter  + 1   ;
 
END loop ;
 return query
select * from TblPriorityGraph;
end
$BODY$;

In the Above function you can see declaration of data and loop execution process.
So we can you loop to insert data to table and get result from table.

So in dynamic way to make a function we can make such function which 
can use all query like insert ,loop,select,return,Declare etc.

Loop basically used to get record from table by year and insert it
 to other table and later on we will get result from it

                            Thanks