Basic programming, .NET technology.

13 - Security - CORS

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file.

Part 2: DI.

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.


CORS: Cross origin resource sharing

  • How to allow CORS
    • AddCors in ConfigureServices method
    • UseCors in Configure method
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});
// services.AddResponseCaching();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
///....
}
}

References:
Share:

5. ASP .Net core - Fundamentals - Configuration

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file.

Part 2: DI.

Part 3: Middleware.

Part 4: Host and Servers.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.


This part shows how to use configuration and how to use Options patterns.

    1. Default configuration
a. ChaninedConfigurationProvider
b. appsettings.json
c. appsettings.[environment].json
d. app secrets
e. environment variables
f. command-line arguments.

Configuration providers that are added later override the previous key setting.

    • JsonConfigurationProvider loads configuration in the following order:
      • appsettings.json
      • appsetings.{Environment}.json
=>  appsetings.{Environment}.json values override keys in appsettings.json

private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
......
}

public WeatherForecast Get()
{
var a = new WeatherForecast
{
// Get value from configureation
Name = _configuration["Name"],
NickName = _configuration["NickName"]
};
return a;
}

  1. Options pattern to read a related configuration
public class PositionOptions
{
public string Title { get; set; }
public string Name { get; set; }
}
...
var positionOptions = new PositionOptions();
Configuration.GetSection("JsonKeySection").Bind(positionOptions);

OR:
positionOptions = Configuration.GetSection(PositionOptions.Position)
.Get<PositionOptions>();

  1. Combining service collection
a. How to register configures option in ConfigureServices method
    • step 0: create Option class
    • step 1: create extension method:
      • first param: IServiveCollection
      • second param: IConfiguration/ or Action<OptionClass>
      • Use: services.Configure method to register configuration
    • step 2: use extension method to register the service.
services.Configure<PositionOptions>( config.GetSection(PositionOptions.Position));
services.Configure<ColorOptions>( config.GetSection(ColorOptions.Color));

b. How to get value of Option at another places
    • Method 1: Use: IServiceProvider serviceProvider to get option value,
Name = _serviceProvider.GetRequiredService<IOptions<PositionOption>>().Value.Name,
NickName = _serviceProvider.GetRequiredService<IOptions<PositionOption>>().Value.Position


    • Method 2:
IOptions<PositionOption> _optionDelegate;
....
// Get value from Option
Name = _optionDelegate.Value.Name,
NickName = _optionDelegate.Value.Position

  1. File configuration provider
  • Json configuration provider
    • use: config.AddJsonFile("MyConfig.json", optional: true, reloadOnChange: true)
      • to add custom config json file
      • This file override settings in the default configuration providers (include environment vars and command-line)
  • XML configuration provider
    • use: AddXmlFile

  1. Others config
a. launchsetting.json
b. web.config


A sample of applying options pattern


References:
Share:

4. ASP .Net core - Fundamentals - Host and Server

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file.

Part 2: Dependency injection.

Part 3: Middleware.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.

In this part, I  got some knowledge about Host and Servers in ASP .Net core

4.1 Host

  • Generic host
  • Web host

- Host is an object that encapsulates:
  • DI
  • Logging
  • Configuration
  • IHostedService implementations
- How to set up a host: Program, Main, CreateHostBuilder
- Default builder setting:
  • CreateDefaultBuilder: content root, host configs, app configs, add logging providers
  • ConfigureWebHostDefault: host configs, set kestrel server....
- Host configuration: how to do? =>  ConfigureHostConfiguration
- App configuration: how to do? => ConfigurAppConfiguration

4.2 Server
  • Kestrel
  • Http.sys
  • Hosting model:
    • in-process hosting
    • out-of-process hosting

References:
Share:

3. Asp.net core - fundamentals - Middleware

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.


Part 1: Startup file.

Part 2: Dependency Injection.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.

This part is to summarise some knowledge concerning the Middleware in Asp .net core.

a. What is middleware
  • Middleware is software added to the pipeline to process requests and responses.
  • When a request comes, it goes through one by one middleware (you can think that all middleware do the common process for each request, response)
  • To use middleware in IApplicationBuilder, use:
    • Run: param: context
    • Use: param: context, next -> to invoke next middleware
    • Map: to branch middleware
  • We have some built-in middleware, we can use them in configure method.
  • Of course, we can also create custom middleware.
b. Order of middleware



--> Endpoint middleware to turn the request into an action method in the controller.



c. How to create a custom middleware
  • step 1: Encapsulate custom middleware in class
    • Convention: {Name}Middleware
    • Include:
      • a constructor with parameter type is "ContextDelegate".
      • A public method is named Invoke or InvokeAsync. This method must:
    • For example:
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
// IMyScopedService is injected into Invoke
public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
{
svc.MyProperty = 1000;
await _next(httpContext);
}
}

  • step 2: create a middleware extension method through IApplicationBuilder:
    • Name convention: Use{MiddlewareName}
using Microsoft.AspNetCore.Builder;
namespace Culture
{
public static class RequestCultureMiddlewareExtensions
{
public static IApplicationBuilder UseRequestCulture(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestCultureMiddleware>();
}
}
}

  • step 3: Call middleware in Configure method
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseRequestCulture();
app.Run(async (context) =>
{
await context.Response.WriteAsync(
$"Hello {CultureInfo.CurrentCulture.DisplayName}");
});
}
}


References:

Share:

2 - [Updated] - ASP .Net core - Fundamentals - Dependency injection

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 1: Startup file in ASP .Net core.

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations.

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.


    In this note, I want to summary some knowledge about DI in Asp.net core.



First, DI is to archive Inversion of Control, solid principle.
We have 3 types of DI: constructor injection, method injection, property injection

The built-in DI of the .net core base on constructor injection.

a. How to register services
  • Register a service in method 'ConfigureServices'
  • Use the "services.Configure" method to config/binding  our configuration to option
  • also can create an extension method of IServicesCollection to compute a group of related service
    • Note: convention : Add{OurServiceName}, for example: AddDataAcessLayer, AddBusinessServices...

b. Service lifetime
  • Transient: short lifetime, create when  service container request, disposed at the end of the request
  • Scoped: create per client request, AddDbContext for example.
  • Singleton: create at the first time that they're requested; disposed of an object only when app shutdown, should consider if we use it, since memory performance

c. Design service for dependency injection
When designing services for dependency injection:
  • Avoid stateful, static classes and members. Avoid creating a global state by designing apps to use singleton services instead.
  • Avoid use Service Locator anti-pattern.
  • Avoid direct instantiation of dependent classes within services. Direct instantiation couples the code to a particular implementation.
  • Make services small, well-factored, and easily tested.
d. Dispose of services: Container takes this responsibility

e. Keyed Service (From ASP.NET Core 8)
When using keyed services:
  • Have an interface with multiple implementations
  • And need to use one of those implementations in different places in your application
Add services by using: AddKeyedSingleton (or AddKeyedScoped or AddKeyedTransient)

builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");

Access a registered service by specifying the key with the [FromKeyedServices]

[HttpGet("big-cache")]
public ActionResult<object> GetOk([FromKeyedServices("big")] ICache cache)
{
    return cache.Get("data-mvc");
}


Ref:
Share:

1 - [Updated] - ASP .Net core - Fundamentals - Startup

 This series is a collection of knowledge about ASP .NET Core. It just is my notes.

Part 2: Dependency Injection

Part 3: Middleware.

Part 4: Host and Servers.

Part 5: Configurations

Part 6: Environment.

Part 7: Logs.

Part 8: Error Handling.

Part 9: Routing.

Part 10: Make an HTTP Request.

Part 11: Static files.

Part 12: Authentication and Authorization.

Part 13: CORS.

I take some notes for the startup file in Asp .net core:

  • Specified when app host is built.
  • ConfigureServices method:
    • called by the host before Configure method
    • Use to set up services for app
    • There is some build-in extension method (AddDbContext, AddEntityFrameworkStores..)
    • Usually used to add business services/ DAL class to dependency injection.
      • You can write an extension method on IServiceCollection to add more services as you want.
  • Configure method
    • used to specify how the app responds to an HTTP request.
    • to configure adding  middleware component to IApplicationBuilder
    • there are some extension methods to  add middleware
    • You can write a new extension method by using IApplicationBuilder  (Ex: write custom middleware)
    • How to write custom middleware
  • Multiple startups
    • for different environments.
    • suffix name matched with the current environment is prioritized, for example (StartupDevelopment)
  • [Updated] - ASP.NET Core 6+
Startup code in the program file because of the minimal hosting model.

  var builder = WebApplication.CreateBuilder(args);
    // Add services to the container.
    builder.Services.AddRazorPages();
    builder.Services.AddControllersWithViews();
    // You can add your user-defined services here
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    // You can add your custom middle ware here
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    ...
    app.Run();


References:

[Microsoft Learn] - App startup in ASP.NET Core

    Share:

    Abstract class và Interface (1)

    We all know the pillars for object-oriented programming are: abstraction, inheritance, encapsulation, polymorphism. The motto is like that, but in an old programming language like C#, how do you apply it to a real problem. Bờm researched and learned, today he understood two keywords: abstraction and inheritance. In this "Hoa Son commentary on the code", Bờm presented: What is an abstract class? What are interfaces?

    1. Abstract class. So we can say that an abstract class cannot have an instance (a concrete object, an instance). Abstract classes are often used to define base classes in inheritance.
    In an abstract class, we can define abstract methods or non-abstract methods.

    A small example will make it easier to understand:
    We define 2 classes: Dog and Cat


    We see that both the Dog and Cat classes share the same properties and methods. We wonder if there is a way to collect common properties and methods? OOP shows that: we can apply abstraction, and inheritance in this case. We abstract the two classes Dog and Cat into an Animal class with common properties and methods, using the abstract keyword to do this.

    The Animal class will be declared as follows



    Refactor Dog and Cat class by using inheritance.


    Through this example, we need to remember:
    - Use abstract class to achieve abstraction, inheritance in object-oriented programming
    - Use the abstract keyword to declare a class or a method as abstract.
    - To implement abstract members of an abstract class, we use the keyword "override" in a subclass.

    2. Interface. We all know C# supports inheritance, but a class can only inherit from one superclass (single inheritance). It does not support multiple inheritances. To solve this problem, we can use an interface. 

    In the subclass, we implement the interface. A subclass can implement many different interfaces. So what is an interface?

    The interface is like a class, can contain methods, properties ... interface contains only declarations (declaration). The classes implement the interface, which will specify the methods and properties of that interface.

    Going back to the above example, we analyze that between the two classes Dog and Cat have their own actions, for example, dogs can bite (bite)... if we declare a common method (Bite) in the abstract class: animal, then we must apply this method to the Cat class (which is not reasonable).

    We could also define a Bite method for the Dog class only, but think further... some other animals have the ability to "bite" too, and we want to abstract this method so we can use it in subclasses (if necessary), in this case, we use interface.

    We can declare an interface like this: We all know C# supports inheritance, but a class can only inherit from one superclass (single inheritance). It does not support multiple inheritances. To solve this problem, we can use an interface. In the subclass, we implement the interface. A subclass can implement many different interfaces. So what is an interface?

    We can declare an interface like this:


    The Dog class implements the interface, here we also see that: by using the interface, the Dog class can realize the dream of multiple inheritances.


    So:
    - Use interfaces for multiple inheritances.
    - Use interfaces to achieve abstraction in OOP.
    - In addition, the use of interfaces also reduces dependencies between classes. Applied to achieve at a theory called "Solid" that you study about programming principles, the design pattern has probably been heard.

    In this article, Mr. Bom only introduces abstract classes and interfaces, the simplest way to achieve two pillars in object-oriented programming is abstraction and inheritance. The problem about using the interface in a more advanced form, to reach the solid programming principle, it lies in another realm... see you in the next "Hoa Son discussion of code".
    Share:

    Featured Posts

    Data type 3 - string type