Customers who sign-up prior to 30/06/2024 get unlimited access to free features, newer features (with some restrictions), but for free for at least 1 year.Sign up now! https://webveta.alightservices.com/
Categories
.Net ASP.Net C# Security

How to prevent CSRF (Cross Site Request Forgery) in ASP.Net MVC

CSRF – Cross Site Request Forgery is a certain type of cyber attack, specifically when using cookies!

A different website would post content into a different domain when the user of the other domain is logged in or in certain other scenarios. CSRF is considered one of the major vulnerabilities and has been in the OWASP top 10 – Cross Site Request Forgery (CSRF).

If you are using token based authentication and if the token is stored in browser’s local storage, CSRF isn’t an issue. This is specifically when using cookies.

Basic Usage:

In .cshtml of web pages inside forms add the following tag:

@Html.AntiForgeryToken()

The above code fragment would render a hidden input element with a long random string.

In the controller class, decorate the action method with the following attribute:

[ValidateAntiForgeryToken]

When the action method is invoked, the validation happens. If the validation succeeds, the action method get invoked. If the validation fails, the action method does not get invoked.

Recommended Usages:

If we forget decorating a post method with [ValidateAntiForgeryToken], we would be susceptible to CSRF attack. Instead we can use a MiddleWare and use the Middleware in the Startup.cs

builder.Services.AddControllersWithViews((options) =>
{
        options.Filters.Add(new  AutoValidateAntiforgeryTokenAttribute());
});

// or

builder.Services.AddMvc((options) =>
{
        options.Filters.Add(new  AutoValidateAntiforgeryTokenAttribute());
});

There are other ways of customizing the middleware, for example if there is a use-case where json data is being sent to a web api and cookies are used for authentication, we can add a customizable header i.e in the calling code we would add the hidden element’s value as header and then make the call.

builder.Services.AddAntiforgery(options =>
{
   options.HeaderName = "X-CSRF-TOKEN-HEADERNAME";
});

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net Security

NWebSec for securing HTTP headers of ASP.Net web applications

NWebSec is a library, that I am familiar and have used in some web applications over the past 3 – 4 years.

Modern web browsers support several HTTP headers for security related purposes. For example, not to cache content, always require HTTPS etc… Most, if not all of these headers can be set at the webserver level instead of at the application level. There are various guides and blog posts for doing the same on HTTP servers.

This blog post is about using NWebSec for setting these headers in ASP.Net web applications. I won’t go over the entire list but I would mention few.

Redirect Validation is one of the OWASP top 10 risks and should happen at the application level. UseRedirectValidation() method validates the redirects and can be configured. – https://docs.nwebsec.com/en/latest/nwebsec/Redirect-validation.html

Configure the X-Frame-Options either at the application level or at the web server level, unless you have a need for your websites to be displayed in iframes of other websites.

Always use https by using the Content Security Policy, Strict Transport Security, Upgrade Insecure Requests.

Apart from these use SecureCookies – https://owasp.org/www-community/controls/SecureCookieAttribute

I am hoping this blog post helps someone.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net C# Grafana Telemetry

Using OpenTelemetry in ASP.Net MVC

OpenTelemetry is pretty much like logs and metrics with distinguishable TraceId’s.

Yesterday and this morning I have experimented with OpenTelemetry in a sample ASP.Net MVC application.

The Primary components are:

  1. A host for Tempo – using Grafana hosted Tempo – https://www.grafana.com. Grafana has a very generous 100GB traces per month in the free tier.
  2. Grafana Agent – As of now, I have used Grafana Agent on Windows laptop, have not configured on Linux production servers yet. Grafana Agent can be downloaded from here. Click on the releases in the right side and choose the Operating System. Here is the link for v0.31.0.
  3. OpenTelemetry SDK for .Net

The OpenTelemetry SDK for .Net are in preview, the API’s might change.

Install the Grafana Agent and update the configuration file. Here is a sample of the config:

server:
  log_level: warn
metrics:
  wal_directory: C:\ProgramData\grafana-agent-wal
  global:
    scrape_interval: 1m
  configs:
    - name: integrations
integrations:
  windows_exporter:
    enabled: true
traces:
  configs:
  - name: default
    remote_write:
      - endpoint: tempo-us-central1.grafana.net:443
        basic_auth:
          username: <YOUR GRAFANA USER_ID>
          password: "<YOUR GRAFANA API KEY>"
    receivers:
      jaeger:
        protocols:
          grpc:
          thrift_binary:
          thrift_compact:
          thrift_http:
      zipkin:
      otlp:
        protocols:
          http:
          grpc:
      opencensus:

Restart the Grafana Service Services.

Add the following pre-release dll’s to your ASP.Net MVC application.

OnLINE Erra, Thota terrorist bastards are spy bastards, they don’t command me, I do whatever I like, because they use invisible spying drone they try to frame me

OpenTelemetry.Api
OpenTelemetry.Exporter.Jaeger
OpenTelemetry.Extensions.Hosting
OpenTelemetry.Instrumentation.AspNetCore
OpenTelemetry.Instrumentation.Http

Now use the following code:

builder.Services.AddOpenTelemetry()
        .WithTracing(builder => builder  .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("Sample-Web"))
            .AddAspNetCoreInstrumentation()
            .AddGrpcCoreInstrumentation()
            .SetErrorStatusOnException()
            .AddJaegerExporter()
            .AddConsoleExporter())
        .StartWithHost();

Run the application.

Now goto your Grafana account, click browse select the traces from the drop down in the top.

Grafana

Clicking on one of the trace id shows the details:

Grafana Traces

There are additional Trace Collectors that can be used on a necessity basis for:

MySQL Client

SQL Server Client

HTTP Client

GRPC

ElasticSearch

AWS

AWS Lambda

You can expect to see some more blog articles regarding Loggin, Tracing and Metrics i.e Observability.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net NLog

Some NLog configuration examples for writing into different log management systems

This blog post is going to discuss few different useful configurations for writing logs using NLog.

  1. Writing directly into AWS CloudWatch

This can be accomplished by adding the NLog.AWS.Logger nuget package. Nuget link. Link for documentation / github.

Although, NLog.AWS.Logger supports other logging frameworks such as Log4Net, Serilog, those are out of context for the current blog post.

In nlog.config enable the extension:

<extensions>
    <add assembly="NLog.AWS.Logger" />
  </extensions>

Define the logger as a target:

<targets>
    <target name="aws" type="AWSTarget" logGroup="NLog.ConfigExample" region="us-east-1"/>
</targets>

2. Writing logs into ElasticSearch

Use NLog.Targets.ElasticSearch nuget package. Nuget URL. Github / documentation link.

Enable the extension:

<extensions>
    <add assembly="NLog.Targets.ElasticSearch"/>
  </extensions>

Define the target, documentation says preferred to wrap in a buffering wrapper:

<targets>
    <target name="elastic" xsi:type="BufferingWrapper" flushTimeout="5000">
      <target xsi:type="ElasticSearch" uri="http://localhost:9200/" />
    </target>
  </targets>

*Instead of hardcoing IP address or “localhost”, I would say use some name such as “elasticsearch” or “kibana” and then use the HOSTS file for mapping to the actual server. Then even if you have several applications on the same server and if the elasticsearch server gets changed, you don’t have to edit all the config files, you can edit just the hosts file. hosts file is located at /etc/hosts on Linux and C:\Windows\System32\drivers\etc\hosts on Windows.

Now we will discuss about 4 different interesting wrappers:

  1. Buffering Wrapper
  2. Async Wrapper
  3. AspNetBuffering Wrapper
  4. FallbackGroup Wrapper

These 4 loggers are wrappers i.e these loggers don’t write logs directly. Instead they are used to wrap other loggers by providing some interesting functionality that can be used to take advantage based upon necessity and use-case.

  1. Buffering Wrapper

Buffers log events and sends in batches.

As mentioned above in the ElasticSearch example, the wrapper would buffer messages and sends in batches.

Documentation

There is a very interesting use-case by using AutoFlushWrapper with BufferingWrapper and the actual target that writes the logs, such as writing the logs only when error happen.

2. Async Wrapper

When you don’t need buffering but at the same time if you don’t want your application to wait until logging is done, this could be useful.

Documentation

3. AspNetBuffering Wrapper

Waits until the completion of ASP.Net request and then sends the logs to the wrapped target.

Documentation

4. FallbackGroup Wrapper

This wrapper can be used for wrapping around multiple targets. For example ElasticSearch followed by Cloudwatch followed by File. i.e if the logger is unable to write to ElasticSearch, it would write to Cloudwatch, if that too failed it would write the logs into file.

Documentation

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net C# DailyReads

Daily Reads 17/12/2022

Build a web API with minimal API, ASP.NET Core, and .NET 6

20 minutes module on Microsoft Learn

Use a database with minimal API, Entity Framework Core, and ASP.NET Core

35 minutes module on Microsoft Learn

Create a full stack application by using React and minimal API for ASP.NET Core

28 minutes module on Microsoft Learn

The above 3 are part of Create web apps and services with ASP.NET Core, minimal API, and .NET 6 learning path.

Canceling abandoned requests in ASP.NET Core – Blog article on how to stop processing of abandoned requests in ASP.Net MVC i.e if a browser loads a page but clicks stop or presses escape key. This way, some server-side resources can be saved.

Two of my favorite and absolutely free desktop based (downloadable) software for diagrams – cloud architecture, UML, Database ER etc… Very useful for small startups and developers.

  1. Diagrams.net
  2. Dia

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net AWS C# DailyReads

Coming soon Daily Reads

As a knowledge worker, I.T developer I have a need to stay up to date with the latest technologies. Similarly millions of I.T developers. I cannot cater to the needs of every knowledge workers or I.T developers but for .Net developers, I am planning to post recommended reads every day. The daily recommended reads would be posted almost every day. The links would be for 3rd party blog posts. The topics would be more about I.T computing, cloud computing, .Net, web development etc…

Subscribe…

Categories
.Net ASP.Net C# NLog

An abnormal way of logging – open for discussion

While I have been brainstorming about something, some small idea came to my mind. People who would read this blog post would either call me stooooopid or might say nice idea.

Anyway the point is, we use logging for various purposes – mostly for troubleshooting. Very verbose logs are a nightmare in terms of performance, storage, retrieval and digging through for the right information. Sometimes, issues troubleshooting becomes a pain because of inadequate information in logs.

What if we log Info and above under normal circumstances, trace and / or debug in certain conditions such as unexpected expectations or errors?

Here is a brief overview of how this might be implemented – in this case, there is a slight memory pressure.

  1. Collect trace and / or debug into Memory log i.e for example if using NLog, use Memory target.
  2. Have some static method that writes the logs from Memory target into a different log target such as File / Database etc…
  3. In the specific conditions such as exception call the static method and in ASP.Net even implement a exception filter to perform the same.

This might be a win-win scenario i.e collecting detailed information in case of unexpected exceptions and error, for any other normal scenario normal logging. Because memory target is being used, very small performance hit, slightly higher memory usage are the drawbacks.

I would love to know how other developers are implementing or handling such use cases.

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net C#

Dependency Injection in ASP.Net MVC Core explained

Dependency Injection is a software development pattern where instead of directly instantiating objects, the objects required by a class are passed in. This helps with maintaining code flexibility, writing unit test cases etc…

The first and foremost thing is to define interfaces and then write implementations. This way, the consuming code needs to know about the methods to be invoked without worrying about the implementation. Software known as Dependency Injection container takes care of instantiating the actual objects as long as the bindings are defined.

This blog post is not about Dependency Injection or Unit Tests but more about how to use Dependency Injection in ASP.Net MVC Core. ASP.Net MVC Core comes with an in-built DI container and supports constructor-based injection i.e instances are passed into the constructor of the consuming class.

There are 3 scopes for objects:

Transient: Every time a class needs an object, a new instance of the requested object is instantiated and passed in. i.e for example if there are 3 classes that need an instance of IService, each class will receive it’s own copy every time even if the three classes are used as part of the same request/response.

Scoped: One object for a particular type is created per request/response and the same object is passed into every class that requests the object processing one request/response cycle.

Singleton: One instance of the class is instantiated for the entire lifetime of the application and the same instance is passed for every class in every request/response cycle.

The use cases for each would vary. Scoped is the default i.e one object for a given type for every class in the same request/response cycle.

Singleton’s are useful in cases such as IConfiguration where the same class can be passed around for getting config information rather than having multiple instances.

Interfaces and implementation classes can be registered by calling the following methods on IServiceCollection for example

AddSingleton<IInterface, Implementation>();
AddScoped<IInterface, Implementation>();
AddTransient<IInterface, Implementation>();

or in Singleton if the object is already instantiated, the object can be passed in by calling:

AddSingleton<IInterface>(instance);

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.

Categories
.Net ASP.Net C#

ViewComponents in ASP.Net and caching ViewComponents

ViewComponent’s are pretty much like PartialView’s but slightly more useful. ViewComponent’s help in rendering part’s of a web page that can be re-used across the website. Also ViewComponent’s output can be cached. This blog article is going to discuss creating ViewComponent’s and caching example.

A ViewComponent is a public class that has a ViewComponent suffix such as HeaderViewComponent or MenuViewComponent etc… ViewComponent class can be decorated with [ViewComponent] attribute or can inherit from ViewComponent class or any other class that’s a ViewComponent. For example some kind of a BaseViewComponent.

ViewComponent must have one method that gets called.

async Task<IViewComponentResult> InvokeAsync()
or
IViewComponentResult Invoke()

The runtime by default searches for the Views in the following locations:

The runtime searches for the view in the following paths:

  • /Views/{Controller Name}/Components/{View Component Name}/{View Name}
  • /Views/Shared/Components/{View Component Name}/{View Name}
  • /Pages/Shared/Components/{View Component Name}/{View Name}

ViewComponent gets invoked from cshtml by using: Component.InvokeAsync()

The call to Component.InvokeAsync() can be wrapped inside <cache> tag helper for caching.

With the concepts discussed above, let’s look at a code sample. Assuming you have a ASP.Net MVC Core test project opened. Now add a new class and name the class TestViewComponent in TestViewComponent.cs.

using Microsoft.AspNetCore.Mvc;


namespace TestProject.ViewComponents
{
    public class TestViewComponent : ViewComponent
    {
        public async Task<IViewComponentResult> InvokeAsync()
        {
            return await Task.FromResult((IViewComponentResult)View("Test"));
        }
    }
}

Now under Views/Shared create a folder and name the folder Components. Under Views/Shared/Components, create another folder Test. Now, Views/Shared/Components/Test folder can contain views for the TestViewComponent. Create a new Test.cshtml under Views/Shared/Components/Test and put some random html content.

<p>Hello from TestViewComponent.</p>

Now somewhere on Views/Home/Index.cshtml place the following invocation:

@(await Component.InvokeAsync("Test"))

If you need to cache the output wrap the invocation inside <cache> tag helper.

        <cache expires-after="@TimeSpan.FromMinutes(5)">
            @(await Component.InvokeAsync("Test"))
        </cache>

Hope this blog post helps someone!

Mr. Kanti Kalyan Arumilli

Arumilli Kanti Kalyan, Founder & CEO
Arumilli Kanti Kalyan, Founder & CEO

B.Tech, M.B.A

Facebook

LinkedIn

Threads

Instagram

Youtube

Founder & CEO, Lead Full-Stack .Net developer

ALight Technology And Services Limited

ALight Technologies USA Inc

Youtube

Facebook

LinkedIn

Phone / SMS / WhatsApp on the following 3 numbers:

+91-789-362-6688, +1-480-347-6849, +44-07718-273-964

+44-33-3303-1284 (Preferred number if calling from U.K, No WhatsApp)

kantikalyan@gmail.com, kantikalyan@outlook.com, admin@alightservices.com, kantikalyan.arumilli@alightservices.com, KArumilli2020@student.hult.edu, KantiKArumilli@outlook.com and 3 more rarely used email addresses – hardly once or twice a year.