1599305880
In this blog, we learn how to implement the AntiXssMiddleware in .NET Core. First, we will understand about the cross-site scripting.
Cross-site scripting is a security vulnerability and a client-side code injection attack. In this attack, the malicious script is injected into legitimate websites. Cross-site scripting allows an attacker to act like a victim user and to carry out the actions that the user can perform. The attacker can access the user’s data as well.
Step 1: Create Asp.NET Core Web Application project in Visual Studio.
Step 2: Select type as API in the next step and create the project. You will find a default controller which is created in the controller folder named as WeatherForecastController.cs
Step 3: Now create a new folder named Middleware in the root directory.
Step 4 : Create a new file AntiXssMiddleware.cs in that Middleware folder.
Step 5: Now add the Newtonsoft.json package into your solution
By doing the above steps you will have below structure in your solution.
Step 6: Now edit the AntiXssMiddlewars.cs file and paste below code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
namespace AntiXssMiddleware.Middleware
{
public class AntiXssMiddleware
{
private readonly RequestDelegate _next;
private ErrorResponse _error;
private readonly int _statusCode = (int)HttpStatusCode.BadRequest;
public AntiXssMiddleware(RequestDelegate next)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task Invoke(HttpContext context)
{
// Check XSS in URL
if (!string.IsNullOrWhiteSpace(context.Request.Path.Value))
{
var url = context.Request.Path.Value;
if (CrossSiteScriptingValidation.IsDangerousString(url, out _))
{
await RespondWithAnError(context).ConfigureAwait(false);
return;
}
}
// Check XSS in query string
if (!string.IsNullOrWhiteSpace(context.Request.QueryString.Value))
{
var queryString = WebUtility.UrlDecode(context.Request.QueryString.Value);
if (CrossSiteScriptingValidation.IsDangerousString(queryString, out _))
{
await RespondWithAnError(context).ConfigureAwait(false);
return;
}
}
// Check XSS in request content
var originalBody = context.Request.Body;
try
{
var content = await ReadRequestBody(context);
if (CrossSiteScriptingValidation.IsDangerousString(content, out _))
{
await RespondWithAnError(context).ConfigureAwait(false);
return;
}
await _next(context).ConfigureAwait(false);
}
finally
{
context.Request.Body = originalBody;
}
}
private static async Task<string> ReadRequestBody(HttpContext context)
{
var buffer = new MemoryStream();
await context.Request.Body.CopyToAsync(buffer);
context.Request.Body = buffer;
buffer.Position = 0;
var encoding = Encoding.UTF8;
var requestContent = await new StreamReader(buffer, encoding).ReadToEndAsync();
context.Request.Body.Position = 0;
return requestContent;
}
private async Task RespondWithAnError(HttpContext context)
{
context.Response.Clear();
context.Response.Headers.AddHeaders();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.StatusCode = _statusCode;
if (_error == null)
{
_error = new ErrorResponse
{
Description = "Error from AntiXssMiddleware",
ErrorCode = 500
};
}
await context.Response.WriteAsync(_error.ToJSON());
}
}
public static class AntiXssMiddlewareExtension
{
public static IApplicationBuilder UseAntiXssMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AntiXssMiddleware>();
}
}
/// <summary>
/// Imported from System.Web.CrossSiteScriptingValidation Class
/// </summary>
public static class CrossSiteScriptingValidation
{
private static readonly char[] StartingChars = { '<', '&' };
#region Public methods
public static bool IsDangerousString(string s, out int matchIndex)
{
//bool inComment = false;
matchIndex = 0;
for (var i = 0; ;)
{
// Look for the start of one of our patterns
var n = s.IndexOfAny(StartingChars, i);
// If not found, the string is safe
if (n < 0) return false;
// If it's the last char, it's safe
if (n == s.Length - 1) return false;
matchIndex = n;
switch (s[n])
{
case '<':
// If the < is followed by a letter or '!', it's unsafe (looks like a tag or HTML comment)
if (IsAtoZ(s[n + 1]) || s[n + 1] == '!' || s[n + 1] == '/' || s[n + 1] == '?') return true;
break;
case '&':
// If the & is followed by a #, it's unsafe (e.g. S)
if (s[n + 1] == '#') return true;
break;
}
// Continue searching
i = n + 1;
}
}
#endregion
#region Private methods
private static bool IsAtoZ(char c)
{
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
#endregion
public static void AddHeaders(this IHeaderDictionary headers)
{
if (headers["P3P"].IsNullOrEmpty())
{
headers.Add("P3P", "CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");
}
}
public static bool IsNullOrEmpty<T>(this IEnumerable<T> source)
{
return source == null || !source.Any();
}
public static string ToJSON(this object value)
{
return JsonConvert.SerializeObject(value);
}
}
public class ErrorResponse
{
public int ErrorCode { get; set; }
public string Description { get; set; }
}
}
#.net
1602560783
In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.
To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.
Sub-topics discussed :
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From new project window, Select Asp.Net Core Web Application_._
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.
Now let’s define DB model class file – /Models/TransactionModel.cs.
public class TransactionModel
{
[Key]
public int TransactionId { get; set; }
[Column(TypeName ="nvarchar(12)")]
[DisplayName("Account Number")]
[Required(ErrorMessage ="This Field is required.")]
[MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
public string AccountNumber { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Beneficiary Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BeneficiaryName { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Bank Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BankName { get; set; }
[Column(TypeName ="nvarchar(11)")]
[DisplayName("SWIFT Code")]
[Required(ErrorMessage = "This Field is required.")]
[MaxLength(11)]
public string SWIFTCode { get; set; }
[DisplayName("Amount")]
[Required(ErrorMessage = "This Field is required.")]
public int Amount { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
}
C#Copy
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContextclass for EF Core.
#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup
1602564619
User registration and authentication are mandatory in any application when you have little concern about privacy. Hence all most all application development starts with an authentication module. In this article, we will discuss the quickest way to use **ASP.NET Core Identity for User Login and Registration **in a new or existing MVC application.
Sub-topics discussed :
ASP.NET Core Identity is an API, which provides both user interface(UI) and functions for user authentication, registration, authorization, etc. Modules/ APIs like this will really be helpful and fasten the development process. It comes with ASP.NET Core Framework and used in many applications before. Which makes the API more dependable and trustworthy.
ASP.NET Core MVC with user authentication can easily be accomplished using Identity.UI. While creating the MVC project, you just need to select Authentication as Individual User Accounts.
The rest will be handled by ASP.NET Core Identity UI. It already contains razor view pages and backend codes for an authentication system. But that’s not what we want in most of the cases. we want to customize ASP.NET Core Identity as per our requirement. That’s what we do here.
First of all, I will create a brand new ASP.NET Core MVC application without any authentication selected. We could add ASP.NET Core Identity later into the project.
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N). From new project window, select ASP.NET Core Web Application.
Once you provide the project name and location. A new window will be opened as follows, Select _Web Application(Model-View-Controller), _uncheck _HTTPS Configuration _and DO NOT select any authentication method. Above steps will create a brand new ASP.NET Core MVC project.
#asp.net core article #asp.net core #add asp.net core identity to existing project #asp.net core identity in mvc #asp.net core mvc login and registration #login and logout in asp.net core
1583378723
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1583377668
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework
1583392491
#Asp.net core #Asp.net core mvc #Core #Asp.net core tutorials #Asp.net core with entity framework