AspNetCore Archives - Learn Smart Coding https://blogs.learnsmartcoding.com/tag/aspnetcore/ Everyone can code! Fri, 29 May 2020 15:34:55 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 209870635 How to use TLS 1.2 in ASP.NET Core 2.0 https://blogs.learnsmartcoding.com/2020/05/29/how-to-use-tls-1-2-in-asp-net-core-2-0-and-above/ https://blogs.learnsmartcoding.com/2020/05/29/how-to-use-tls-1-2-in-asp-net-core-2-0-and-above/#respond Fri, 29 May 2020 15:34:55 +0000 https://karthiktechblog.com/?p=504 In this short post, I will show how to use TLS 1.2 in ASP.NET Core 2.0 and the above version. Why TLS 1.2 ? Client-Server applications use the TLS protocol to communicate across a network in a way designed to prevent eavesdropping and tampering. Since applications can communicate either with or without TLS (or SSL), […]

The post How to use TLS 1.2 in ASP.NET Core 2.0 appeared first on Learn Smart Coding.

]]>
In this short post, I will show how to use TLS 1.2 in ASP.NET Core 2.0 and the above version.

Why TLS 1.2 ?

Client-Server applications use the TLS protocol to communicate across a network in a way designed to prevent eavesdropping and tampering. Since applications can communicate either with or without TLS (or SSL), it is necessary for the client to indicate to the server the setup of a TLS connection. Read more on Transport Layer Security

Encryption protocols like Transport Layer Security (TLS), Secure Sockets Layer (SSL) are intended to keep data secure when being transferred over a network.

Applying fix to use TTLS 1.2 in ASP.NET Core 2.0

In the Program.cs file, use the below code to configure the TLS 1.2.

 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
           WebHost.CreateDefaultBuilder(args)
                .UseKestrel(opt =>

                {
                    opt.AddServerHeader = false;
                    opt.ConfigureHttpsDefaults(s =>
                    {
                        s.SslProtocols = SslProtocols.Tls12 ;
                    });
                })
                .ConfigureLogging(builder =>
                {
                    builder.ClearProviders();
                    builder.AddSerilog();
                })
               .UseStartup();
How to use TLS 1.2 in ASP.NET Core 2.0
How to use TLS 1.2 in ASP.NET Core 2.0

Though you can configure TLS 1.2 in Web applications, it will be a good idea to force the webserver to use the minimum security level of TLS 1.2.

There is a good article in MSDN How to enable TLS 1.2

Though this solution could protect the application to support TLS 1.2, the right way of implementing TLS 1.2 and above is to disable the lower version of TLS in the webserver.

The right way of TLS implementation

How to Enable/Disable TLS 1.0, 1.1 and 1.2 in Windows Server using IISCrypto tool

Related Post

You might be interested in the below security-related post, take a look.

Conclusion

In this post, I showed how to use TLS 1.2 in ASP.NET Core 2.0. I also suggested applying a fix in the webserver to support only TLS 1.2 and above versions. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to use TLS 1.2 in ASP.NET Core 2.0 appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/05/29/how-to-use-tls-1-2-in-asp-net-core-2-0-and-above/feed/ 0 504
Working with optional body parameters in ASP.NET Core 2.2 https://blogs.learnsmartcoding.com/2020/04/04/working-with-optional-body-parameters-in-asp-net-core-2-2/ https://blogs.learnsmartcoding.com/2020/04/04/working-with-optional-body-parameters-in-asp-net-core-2-2/#respond Sat, 04 Apr 2020 20:33:43 +0000 https://karthiktechblog.com/?p=444 Working with optional body parameters in ASP.NET Core 2.2 is now possible and I will show how to solve the issue in this post. Optional parameter exists in .Net for a long time. Specifying the default value used to be enough to mark them as optional. However, marking a body parameter in a Web API […]

The post Working with optional body parameters in ASP.NET Core 2.2 appeared first on Learn Smart Coding.

]]>
Working with optional body parameters in ASP.NET Core 2.2 is now possible and I will show how to solve the issue in this post. Optional parameter exists in .Net for a long time. Specifying the default value used to be enough to mark them as optional. However, marking a body parameter in a Web API action method is not going to work if you are working with .NET Core 2, 2.1 and 2.2 versions.

Let me explain the problem that you might face and a solution to solve the problem.

An issue in accepting body parameter as optional

I have a model class in my action method and that reads the content from the body as shown below.

        // POST api/values
        [HttpPost]
        public IActionResult Post([FromBody]ModelClass request = null)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            return Ok();
        }

Here is the problem, as soon as you include an attribute [FromBody], MVC binding will trigger. If you did not send content in the request body, you will see an error as shown below.

{
  "": [
    "A non-empty request body is required."
  ]
}

This is an existing issue in .NET Core 2.0. Optional body parameters no longer work since upgrading to .NET Core 2.0 #6920

Solution

One of the solutions is to read the content from the request body and then process it if it was sent in the request.

 string body;
            SomeClassModel model = null;
            using (var reader = new StreamReader(Request.Body, Encoding.UTF8, true, 1024, true))
            {
                body = reader.ReadToEnd();
            }

            if (!string.IsNullOrEmpty(body))
            {
               finalModel = JsonConvert.DeserializeObject(body);
            }

This way the body parameters can be made optional and custom validation can be implemented in case you need to validate a JSON string in the body parameter.

Related Posts

Implement create, read, update, and delete functionalities using Entity Framework Core

Conclusion

In this post, I showed how to work with optional body parameters in ASP.NET Core 2.2. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Working with optional body parameters in ASP.NET Core 2.2 appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/04/04/working-with-optional-body-parameters-in-asp-net-core-2-2/feed/ 0 444
How to cast int to enum in C# https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/ https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/#respond Wed, 15 Jan 2020 03:03:36 +0000 https://karthiktechblog.com/?p=326 Introduction In this short post, I show How to cast int to enum in C#. We have used an enumeration type (or enum type) in our day to day programming. Enum is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, we used […]

The post How to cast int to enum in C# appeared first on Learn Smart Coding.

]]>
Introduction

In this short post, I show How to cast int to enum in C#. We have used an enumeration type (or enum type) in our day to day programming. Enum is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, we used the enum keyword and specified the names of enum members as shown in below example.

public enum OrderStatus
{
Received = 1,
InProgress = 2,
Processed = 3,
Shipped = 4
}

How to convert int to enum ?

Let’s take an example to demonstrate real time scenario. Consider we have a field that represents order status for a given product order.

public OrderStatus Status {get; set;}

OrderStatus is the enum that is defined with various status. E.g. Received, InProgress, Processed and Shipped.

Say you need to convert int or string to enum, it is easy to do so.

OrderStatus variableName = (OrderStatus)Enum.Parse(typeof(OrderStatus), yourStringVariable);

Yes, it is that easy to cast int to enum type.

Validate enum property in model

Say, your enum property needs to be validated in a given model, simple use the EnumDataType as shown below.

[Required]
[EnumDataType(typeof(OrderStatus), ErrorMessage = "Provide initial order status")]
public OrderStatus Status { get; set; }

Resource

Read more on Enum

Interested in Azure certification? Take a look at my post EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE

Conclusion

In this short post, I showed how to cast int or string to enum in C#. That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to cast int to enum in C# appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/15/how-to-cast-int-to-enum-in-c-sharp/feed/ 0 326
How to: Create API documentation using OpenAPI & Swagger https://blogs.learnsmartcoding.com/2020/01/10/how-to-create-api-documentation-using-openapi-and-swagger/ https://blogs.learnsmartcoding.com/2020/01/10/how-to-create-api-documentation-using-openapi-and-swagger/#respond Fri, 10 Jan 2020 10:45:36 +0000 https://karthiktechblog.com/?p=301 Introduction In this post, I show how to create API documentation using OpenAPI & Swagger. This post will help to cover a part of knowledge required to complete Azure AZ-203 certification. To start with Azure AZ-203 certification, take a look at my post EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE What is API documentation ? […]

The post How to: Create API documentation using OpenAPI & Swagger appeared first on Learn Smart Coding.

]]>
Introduction

In this post, I show how to create API documentation using OpenAPI & Swagger. This post will help to cover a part of knowledge required to complete Azure AZ-203 certification.

To start with Azure AZ-203 certification, take a look at my post EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE

What is API documentation ?

API documentation is the information that is required to successfully consume and integrate with an API. This can be in the form of technical writing, code samples and examples for better understanding how to consume an API.

API Documentation using OpenAPI & Swagger

When consuming a Web API, understanding its various methods can be challenging for a developer who is new to consume our API.

Swagger, also known as OpenAPI, solves the problem of generating useful documentation and help pages for Web APIs.

In this post, Swashbuckle.AspNetCore is shown with a demo app.

Swashbuckle.AspNetCore is an open source project for generating Swagger documents for ASP.NET Core Web APIs.

Additional Resource For Swagger

Swagger

Background of Demo App

I created an demo App with N-Tier architecture that uses Azure SQL database as back end database. Demo app has a controller called Product which does CURD functionality.

The full demo application is available for free and you may download from my GitHub repository.

To download this demo related code, pick branch code “feature/ImplementCURDFunctionality”

Get Started

In this demo app, I will be using my existing asp.net core API app and add code to start showing API documentation using Swagger’s OpenAPI

Setup and Configure OpenAPI & Swagger

Step 1

Install nuget package Swashbuckle.AspNetCore. and some minimum setup to start showing API documentation automatically.

Step 2

Add Swagger configuration to the ConfigureServices method from the Startup class.

services.AddSwaggerGen(
                options =>
                {
                    var assembly = typeof(Startup).Assembly;
                    var assemblyProduct = assembly.GetCustomAttribute().Product;

                    options.DescribeAllEnumsAsStrings();
                    options.DescribeAllParametersInCamelCase();
                    options.DescribeStringEnumsInCamelCase();

                    var info = new Info
                    {
                        Version = "v1",
                        Title = "KarthikTechBlog:Shopping - V1",
                        TermsOfService = "None",
                        Contact = new Contact()
                        {
                            Name = "Karthik",
                            Email = "karthiktechblog.com@gmail.com",
                            Url = "http://www.karthiktechblog.com"
                        }
                    };

                    options.SwaggerDoc("v1", info);

                    // Set the comments path for the Swagger JSON and UI.
                    var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                    var xmlPath = Path.Combine(basePath, "KarthikTechBlog.xml");
                    options.IncludeXmlComments(xmlPath);

                    options.CustomSchemaIds(x => x.FullName);
            }
            );

Step 3

Next is to add Swagger in the request pipeline.

// Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
            });

Step 4

Add required attributes to the controller action methods to show in API documentation. Adding ProducesResponseType attribute to the method help determines what is expected from API endpoint.

[HttpGet("")]
[ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status404NotFound)]
public async Task GetProducts()
{
	var products = await ProductService.GetProductsAsync();

	var model = Mapper.Map>(products);
	return new OkObjectResult(model);
}

To read more, visit how to implement create, read, update, and delete functionalities using Entity Framework Core

Create API documentation using OpenAPI & Swagger
Create API documentation using OpenAPI & Swagger

Conclusion

In this post, I showed how to create API documentation using OpenAPI & Swagger. This post is part of learning track for azure AZ-203 certification.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post How to: Create API documentation using OpenAPI & Swagger appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2020/01/10/how-to-create-api-documentation-using-openapi-and-swagger/feed/ 0 301
Policy and Resource based authorization in ASP NET Core https://blogs.learnsmartcoding.com/2019/12/26/policy-and-resource-based-authorization-in-asp-net-core/ https://blogs.learnsmartcoding.com/2019/12/26/policy-and-resource-based-authorization-in-asp-net-core/#respond Thu, 26 Dec 2019 10:53:01 +0000 https://karthiktechblog.com/?p=250 Introduction In this post, we will see how to implement Policy and Resource based authorization in ASPNETCore. There are instance where we need to validate the incoming data model. We will see how to validate the data model and authorize. In our example, say we have two entities namely, Category and Product. Examples in this […]

The post Policy and Resource based authorization in ASP NET Core appeared first on Learn Smart Coding.

]]>
Introduction

In this post, we will see how to implement Policy and Resource based authorization in ASPNETCore. There are instance where we need to validate the incoming data model. We will see how to validate the data model and authorize.

In our example, say we have two entities namely, Category and Product. Examples in this post shows how to validate the policy requirement along with the incoming model data which is inside the request body.

Are you looking for Azure AZ-203 certifications? Learn more by visiting below link.

 public class Product
    {
        public int Id { get; set; }
        [Required]
        [MinLength(5), MaxLength(200)]
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime? AvailableSince { get; set; }
        public int StockCount { get; set; }
        public int CategoryId { get; set; }
        public Category Category { get; set; }
        public List ProductImages { get; set; }
        public Status Status { get; set; }
    }

 public class Category
    {
        public int Id { get; set; }
        [Required]
        [MinLength(2), MaxLength(200)]
        public string Name { get; set; }
        public Status Status { get; set; }
    }

An authorization policy consists of one or more requirements. Policy is registered as part of the authorization service configuration, in the ConfigureServices method in the startup class.

Let us register two policy in our startup class as mentioned above.

 
services.AddAuthorization(options =>
            {
                options.AddPolicy("ProductAuthorizationPolicy", policy =>
                       policy.Requirements.Add(new ProductRequirement()));

                options.AddPolicy("CategoryAuthorizationPolicy", policy =>
                      policy.Requirements.Add(new CategoryRequirement()));

            });
Configure policy requirement in ConfigureService method

ProductRequirement and CategoryRequirement are the class which implements IAuthorizationRequirement. IAuthorizationRequirement is from the namespace Microsoft.AspNetCore.Authorization

Let’s take a look at CategoryRequirement Resource based Authorization handler.

Policy and Resource based authorization in ASPNETCore

{
    public class CategoryAuthorizationHandler :
    AuthorizationHandler
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       CategoryRequirement requirement,
                                                       Category resource)
        {
            if (context.User.Identity?.Name != null && resource.Name != null)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }

    public class CategoryRequirement : IAuthorizationRequirement { }
}

IAuthorizationService has two AuthorizeAsync method overloads: one accepting the resource and the policy name and the other accepting the resource and a list of requirements to evaluate.

Task AuthorizeAsync(ClaimsPrincipal user,
                          object resource,
                          IEnumerable requirements);
Task AuthorizeAsync(ClaimsPrincipal user,
                          object resource,
                          string policyName);
Policy based authorization in ASP NET Core

Now, how do we call this policy from an API endpoint and validate the requirement?

We have a controller for Category and that will look as shown below. The following code sample assume authentication has run and set the User property.

  [Route("api/[controller]")]
    [ApiController]
    public class CategoryController : ControllerBase
    {
        public CategoryController(IAuthorizationService authorizationService)
        {
            AuthorizationService = authorizationService;
        }

        public IAuthorizationService AuthorizationService { get; }

        // POST api/values
        [HttpPost]     
        public async Task Post([FromBody] Category category)
        {            
            /*
             This is a way the policy is manually triggered with the resource E.g. Category in this case
             */
            AuthorizationResult authResult = await AuthorizationService.AuthorizeAsync(User,
                category, "CategoryAuthorizationPolicy");

            if (!authResult.Succeeded)
            {
                return Forbid();
            }

            return Ok();
        }
    }
policy based authorization in ASPNETCore

If you wonder how to validate data model in a HTTPost call, here is an example.

In this below sample, we have an end point which accepts Product model in the request body

{
    public class ProductAuthorizationHandler : AuthorizationHandler
    {
        public ProductAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
        {
            HttpContextAccessor = httpContextAccessor;
        }
        public IHttpContextAccessor HttpContextAccessor { get; }

        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
                                                       ProductRequirement requirement)
        {
            Product productModel;
            using (var reader = new StreamReader(HttpContextAccessor.HttpContext.Request.Body))
            {
                var bodyContent = reader.ReadToEnd();
                productModel = JsonConvert.DeserializeObject(bodyContent);
            }

            if (context.User.Identity?.Name!=null && productModel!=null&& productModel.Price>3) 
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
    public class ProductRequirement : IAuthorizationRequirement { }
}
Policy and Resource based authorization in ASP NET Core

We have Product controller and code sample is below.

 [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {    
        // POST api/values
        [HttpPost]
        [Authorize(Policy = "ProductAuthorizationPolicy")]
        public IActionResult Post([FromBody] Product product)
        {
            return Ok();
        }        
        
    }
Resource based authorization in ASPNETCore

This is just an example of how to validate the incoming data model which is in the request body.

In order to access the request body, we need IHttpContextAccessor to be injected by DI. With the instance of IHttpContextAccessor, the request body is read and converted to the string to the required model.

Do not forget to configure the IHttpContextAccessor in the ConfigureServices method in the startup class.


services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

If you would like to learn simple authorization, here is the link to it Simple Authorization.

Conclusion

In this post, we looked at how to implement Policy and Resource based authorization in ASPNETCore. Also, this post covered how to validate the incoming data model.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

The post Policy and Resource based authorization in ASP NET Core appeared first on Learn Smart Coding.

]]>
https://blogs.learnsmartcoding.com/2019/12/26/policy-and-resource-based-authorization-in-asp-net-core/feed/ 0 250