Saturday, October 27, 2018

.Net Core | Http Request Pipeline & Middleware

In .Net Core web application initialization and startup has been totally changed.

Configure Method of Startup class configures Http Request pipeline.

  • Global.asax has been removed. 
  • ini, xml and json files taken place to use in configuration 


Middleware

Middleware is software that's assembled into an app pipeline to handle requests and responses.
  • A Middleware can choose whether the request has to pass to next component or it can terminate the chain that is called Short-Circuiting the pipeline. Middleware3 is doing it in below example.
  • Middleware can perform work before calling next component and can perform work after the next component call finishes.




Run, Map and Use methods 


Run: First occurrence of Run terminates the executor branch or request pipeline if no branches. 



public class Startup
{
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async context =>
            {
                await context.Response.WriteAsync("Hello megabyteland.blogspot.com");
            });
        }
}

Use: To configure multiple middlewares you need to use Use method. Second parameter of Use is delegate for next middleware defined in the pipeline.
public class Startup
{
  public void Configure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                // Do work before invoking next middleware.
                await next.Invoke();
                // Do work after invoking next middleware.
            });

            app.Run(async context =>
            {
                await context.Response.WriteAsync(("Hello megabyteland.blogspot.com");
            });
        }
}


Wednesday, October 17, 2018

.Net Core | GDPR (General Data Protection Regulation)

The "General Data Protection Regulation" (GDPR) (Regulation (EU) 2016/679) is a regulation by which the European Parliament, the Council of the European Union and the European Commission intend to strengthen and unify data protection for all individuals within the European Union (EU).

Cookie consent feature allows you to ask and track consent from users for storing personal information.
If app has CheckConsentNeeded set to true than application prompt user with below screen.






If user has not consented (not Accepted) for collecting his data then non-essential cookies would not be sent to the browser.

In this case only essential Cookies would be sent to the browser.
Session state and TempData would not work because Session and TempData cookies are not essential.
However, in this case you can make them essential to work.

Monday, October 15, 2018

.Net Core | Start with MVC

Using MVC in .Net Core
  1. Register MVC as middleware in http Request Pipeline
    app.UseMvc()
    You can also configure Routing with registration of MVC as middleware.           

    Below method can be used if your controller is Home, action in that is Index.
     app.UseMvcWithDefaultRoute()
    If you have different name controller/action than you can configure route as given below
    Id is optional parameter
     app.UseMvc(routes => 
                  routes.MapRoute(
                        name: "default",                   
                        template: "{controller=EquityHome}/{action=Login}/{Id?}") 
                   )
  2.   
  3. Inject MVC in IOC Container
     services.AddMvc()
    You can set .Net Core version as well with injecting MVC using SetCompatibilityVersion method.
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)


  4. Configure HttpRequest pipeline with some important and required features/services
    All these services have IApplicationBuilder parameter and returns it back IApplicationBuilder after completion of operation (we no need to mention it)
    • app.UseHttpsRedirection()
      Enables security by redirecting all http requests to https
    • app.UseStaticFiles()
      • UseStaticFiles(IApplicationBuilder) Enables static file serving for the current request path
      • UseStaticFiles(IApplicationBuilder, StaticFileOptions) Enables static file serving with the given options
      • UseStaticFiles(IApplicationBuilder, String)
        Enables static file serving for the given request path

    • app.UseCookiePolicy()
      Different cookie policy options can be set with CookiePolicyOptions parameter
    • app.UseStatusCodePagesWithRedirects("~/errors/{0}.html")
      Can be used to redirect to custom error page, where parameter {0} is error status code
    • app.UseStatusCodePagesWithReExecute("~/errors/{0}.html")
      Can be used to redirect to custom error page, where parameter {0} is error status code.
      This method re-executes http request pipe line with given url 
    • app.UseDeveloperExceptionPage()
    • This method display error details on web page.(Yellow error page)
  5. Implement security using, It enforces browsers to use https
    app.UseHsts()

  6. MVC Application architecture with .Net Core   

  1. Microsoft.AspNetCore.App provide all .net core features.
  2. site.css is java script is empty java script file for development and site.min.css is for other environments.

Friday, October 5, 2018

.Net Core | Security - Enforce HTTPS

Enforce HTTPS in ASP.Net Core

Microsoft recommends below 2 methods to use that enforces HTTPS

  • UseHttpsRedirection 
  • UseHsts

1. UseHttpsRedirection 


RequireHTTPS Attribute not Recommended:
can be used at controller level to enforce HTTPS, but its not recommended for Web APIs, because API clients may not understand redirection of HTTP to HTTPS, as a result they may not serve request and return with http status code 404 bad request, they may send information over http.      

[RequireHttps]
public class HomeController: Controller
{}

Add below method in Configure method of Startup.cs.  
app.UseHttpsRedirection();

It uses default values of RedirectionStatusCode and HttpsPort
HttpsRedirectionOptions.RedirectStatusCode (Status307TemporaryRedirect).
HttpsRedirectionOptions.HttpsPort (null)

default HTTPS port is 447

If you want to change RedirectionStatusCode and/or HttpsPort than
Add below middleware into ConfigureServices method, else UseHttpsRedirection in Configure is sufficient.
            services.AddHttpsRedirection(options => {
                options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                options.HttpsPort = 5001;
            });


2. UseHsts

Per OWASP, HTTP Strict Transport Security (HSTS) is an security enhancement using a response header.
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

When a browser(supports HSTS) receives this header it stores configuration for the domain than based on configuration browser ensures 
  • Prevents communications using HTTP
  • Forces to use HTTPS
  • Prevents to use any invalid or untrusted certificates
  • Disables prompts that allow a user to temporarily trust such invalid certificates

    There are few limitations
  • The client should support HSTS
  • Requires at least one successful HTTPS request to establish the HSTS policy
  • Application must check every HTTP request and redirect/reject the HTTP request

HSTS should not be used with development environment as its highly cacheable.  


  • IncludeSubDomains: Says to include sub-domains as well for this configuration
  • MaxAge: Browser cache the rule for the specified time duration. (For Production environment recommended is 1 year )
  • ExcludeHosts: Excludes specific hosts from this rule
  • Preload: It says browser to include your domain into its Preload list
Be careful in Production environments to set Preload = true and higher MaxAge(1 year). If you are sure that you would serve HTTPS support for your domain / sub-domain more than specified time than you should set it.
Removal of the rule from browsers might take months.
Because its become hard code rule for browsers until new updates of browsers not received.
If you stop support of HTTPS for your domain and change change configuration before previous time span, settings may take months to update client's browser and your domain might return with 402 Bad Request.  

CI/CD - Safe DB Changes/Migrations

Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...