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

Scalar Function in SQL

To Get data repeatedly in many Store Procedure. We will write a query or statement that execute to provide desired data. 

The main advantage of the function is that it can be used in SQL Procedure. 

  Built In Function

Like some function are already built in SQL i.e is used to get value which is called built in function. 
e.g 
  DateName(year,dob),
  DayName()


  User Defined Function

We can write our function to get desired data.Lets see how to write it

CREATE FUNCTION functioname
(
@mydate AS DATETIME
)
RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN
  DATENAME(DW, @mydate)+ ', '+
  DATENAME(DAY, @mydate)+ ' '+
  DATENAME(MONTH, @mydate) +', '+
  DATENAME(YEAR, @mydate)
 
END


This Function Can be used in any Procedure to get value

Lets see how

 
SELECT Empname,
[dbo].[functioname](DOB) FROM Employee



 

Introduction to SQL

SQL stands for Structured Query Language.

SQL is a standard language for accessing and manipulating databases and records

It helps to Manage Data in database according to Our Need.

Let see what we can do with SQL


1.Create a Database .

2.Create table inside database to store data.

3.Insert data using SQL Query.

4.Update data using SQL Query

5.Delete data using SQL Query

6.Retrive Record from Datable as per our need.

7.Set permission to Database and Table.

8.We can create Store Procedure to fetch record or manipulate record.


We have to use Some Command to Manipulate Database record.

Insert,Update,Delete,Select...........etc.

There are Some Syntax in SQL which is used to Manipulate record in database

which is ANSI standard Syntax and Command

.Like To Fetch all records From Table we will write

select * from TableName

To Delete Record From Table

Delete TableName where ID=X

This will delete record from table where ID is X






Order by In SQL

  Order by in Sql is used to sort record in ascending or desending order


We will write query like 


SELECT X, Y, ...
FROM mytable
ORDER BY x, y,Z ... ASC|DESC;


by default it gives record in ascending order but get record in ascending order we will use order by Desc



Example

StudentIDStudentNameAgeMarks
1Navneet1182
2

Nitesh1690

Select * from Studenttable order by age  desc


Result as below

 

StudentIDStudentNameAgeMarks
2Nitesh1690
1Navneet1182