.NET 8 Archives - Tech Insights https://reactconf.org/category/net-8/ Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Fri, 05 Jan 2024 06:04:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 .NET 8 Archives - Tech Insights https://reactconf.org/category/net-8/ 32 32 230003556 Implement JWT Authentication and Authorization in ASP.NET Core https://reactconf.org/implement-jwt-authentication-and-authorization-in-asp-net-core/ https://reactconf.org/implement-jwt-authentication-and-authorization-in-asp-net-core/#respond Thu, 04 Jan 2024 07:06:38 +0000 https://reactconf.org/?p=290 JSON Web Token (JWT) is a common authentication method in modern web development  In this article, we will explore How to implement JWT Authentication and Authorization in ASP.NET Core application. …

The post Implement JWT Authentication and Authorization in ASP.NET Core appeared first on Tech Insights.

]]>
JSON Web Token (JWT) is a common authentication method in modern web development  In this article, we will explore How to implement JWT Authentication and Authorization in ASP.NET Core application.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web API” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Install the JwtBearer NuGet Package

Add the “Microsoft.AspNetCore.Authentication.JwtBearer” NuGet package to your project.

  • Select the  project Solution in the Explorer window
  • Right-click and select “Manage NuGet Packages”
  • In the NuGet Package Manager window, search for the “Microsoft.AspNetCore.Authentication.JwtBearer”
  • Click on the Install button.

Another way to install the package “Microsoft.AspNetCore.Authentication.JwtBearer”   via Package Manager Console

Specify a Secret Key in the appsettings.json file

Add the following information in the appettings.json file.

 "JWT": {
   "key": "YouSecreteKeyforAuthenticationtovalidateApplication",
   "Issuer": "reactconf.org",
   "Audience": "reactconf.org"
 },

Configure JWT  authentication in the Program.cs file

using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.


builder.Services.AddAuthentication(option =>
{
    option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(opt =>
{
    opt.TokenValidationParameters = new TokenValidationParameters
    {
     ValidIssuer = builder.Configuration["Jwt:Issuer"],
     ValidAudience= builder.Configuration["Jwt:Audience"],
     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])),
     ValidateIssuer=true,
     ValidateAudience=true,
     ValidateLifetime=false,
     ValidateIssuerSigningKey=true

    };
});
    
    
    
   
builder.Services.AddControllers();

builder.Services.AddSingleton<IDepartment,DepartmentServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.


app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

Create a User Model in ASP.NET Core

For storing the login credentials of the users, we need to create a class named Login in the Model folder.

namespace dotNet8CRUDWebAPI.Model
{
    public class Login
    {
        public string username {  get; set; }
        public string password { get; set; }
    }
}

Generate JWT Tokens

We are Creating another controller named “TokenGenerate”  to generate and validate the JWT. Create action method “Post”,  this method generated token in response to an initial request to the API, then use it for authorization in all subsequent requests.

using dotNet8CRUDWebAPI.Model;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TokenGenerateController : ControllerBase
    {
        private readonly IConfiguration _configuration;
        //private SymmetricSecurityKey _key;
       

        public TokenGenerateController(IConfiguration configuration)
        {
            _configuration = configuration;
           
        }
        [HttpPost]
        public IActionResult Post(Login  loginRequest)
        {
            if (loginRequest.username == "Admin" || loginRequest.password == "Passw0rd")
            {
                var issuer = _configuration["Jwt:Issuer"];
                var audience = _configuration["Jwt:Audience"];
                var _key =  Encoding.ASCII.GetBytes(_configuration["Jwt:Key"]);


                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new[]
                    {
                        new Claim("Id",Guid.NewGuid().ToString()),
                        new Claim(JwtRegisteredClaimNames.Sub, loginRequest.username),
                        new Claim(JwtRegisteredClaimNames.Email, loginRequest.username),
                        new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
                   }),

                    Expires = DateTime.UtcNow.AddMinutes(10),
                    Issuer = issuer,
                    Audience = audience,
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(_key), SecurityAlgorithms.HmacSha256Signature)
                };



                var tokenHandler = new JwtSecurityTokenHandler();
                var token = tokenHandler.CreateToken(tokenDescriptor);
                var jwttoken = tokenHandler.WriteToken(token);
                var stringToken = tokenHandler.WriteToken(token);
                return Ok(stringToken);
            }


            return Ok("Unauthorized");
        }
    }
}

Handling Authorization Checks

To handle authorization checks, you can use the [Authorize] attribute on controller and actions method.


namespace dotNet8CRUDWebAPI.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private readonly IDepartment _department;

        public DepartmentController(IDepartment department)
        {
           _department = department;
        }

        [HttpGet]
        public IActionResult Get([FromQuery] bool? isActive=null)
        {
            return Ok(_department.GetAllList(isActive));
        }
   }
}

Now simply run the application or press F5 to run

Generate Token

Authorization Checks

See More: .NET 8: How to make API faster in Asp.Net Core

The post Implement JWT Authentication and Authorization in ASP.NET Core appeared first on Tech Insights.

]]>
https://reactconf.org/implement-jwt-authentication-and-authorization-in-asp-net-core/feed/ 0 290
.NET 8: How to make API faster in Asp.Net Core https://reactconf.org/net-8-how-to-make-api-faster-in-asp-net-core/ https://reactconf.org/net-8-how-to-make-api-faster-in-asp-net-core/#respond Wed, 03 Jan 2024 09:28:42 +0000 https://reactconf.org/?p=267 Developing a Web API is a common task in Web development and Mobile Apps, but improving the performance of API is the real challenge. In this article, we will explore …

The post .NET 8: How to make API faster in Asp.Net Core appeared first on Tech Insights.

]]>
Developing a Web API is a common task in Web development and Mobile Apps, but improving the performance of API is the real challenge. In this article, we will explore How to make API faster in .NET 8 Asp.Net Core using Distributed Caching (Redis).

Why Redis Cache?

Before we implementation of  Redis Cache, let’s understand why we need Redis Cache. In any application, fetching data from the database or any other different resources is a time-consuming process. To improve this, we use caching.

Redis Cache stores the frequently accessed data in-memory and retrieves it at a much faster rate compared to traditional databases.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web API” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Install Redis

Install Redis Cache using NuGet Package or run the following command in Package Manager Console.

Implement distributed Caching?

Open the Program.cs file and configure.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddOutputCache(option => option.DefaultExpirationTimeSpan = TimeSpan.FromMinutes(10))
    .AddStackExchangeRedisCache(opt =>
    {
        opt.InstanceName = "TodosWebAPI";
        opt.Configuration = "localhost";
    }
    );


var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseOutputCache();
app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Create a Model

namespace dotNet8CRUDWebAPI.Model
{
    public class TodoUserList
    {
        public int userId {  get; set; }
        public int id { get; set; }
        public string title { get; set; }
        public bool completed { get; set; }
    }
}

Create a Controller

Open the controller create action method and Add the [OutputCache] attribute.

using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {

        [HttpGet("GetDatafromOtherSource")]
        [OutputCache]
        public async Task<IActionResult> GetDatafromOtherSource()
        {
            using var httpClient = new HttpClient();
            var response = await httpClient.GetFromJsonAsync<TodoUserList[]>("https://jsonplaceholder.typicode.com/todos");
            return Ok(response); 
        }
    }
}

Now simply run the application or press F5 to run

As you can see, caching has allowed us to reduce the response time all the way down to 1.2 s.  that’s all I have to say for now, I hope you found this information helpful.

See More: .NET 8: ASP.Net Core Web API CRUD Operations

The post .NET 8: How to make API faster in Asp.Net Core appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-how-to-make-api-faster-in-asp-net-core/feed/ 0 267
.NET 8: ASP.Net Core Web API CRUD Operations https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/ https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/#comments Tue, 02 Jan 2024 10:40:14 +0000 https://reactconf.org/?p=245 In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete …

The post .NET 8: ASP.Net Core Web API CRUD Operations appeared first on Tech Insights.

]]>
In .NET 8, Developing a CRUD (Create, Read, Update, Delete) API using In-memory collection is a common task in web development. In this article, we will explore building a complete .NET 8 ASP.NET Core Web API CRUD Operations. With a practical use case.

What is an API?

  • API stands for Application Programming Interface.
  • API is a software intermediary that allows different software applications to communicate and exchange data.

What is RESTful API?

  1. REST stands for Representational State Transfer.
  2. REST is a software architecture that imposes conditions on how an API should work.
  3. RESTful API is an interface that two computer systems use to exchange information securely over the internet.

Create an Asp.NET Core Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  1. Open the visual studio (IDE).
  2. Click on the “Create new project” option.
  3. Choose “ASP.NET Core Web API” from the list of available templates.
  4. Click the Next button.
  5. The configure a new project, specify the name and location of your project.
  6. Click the “Next” button.
  7. Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  8. Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  9. Click the “Create” button

Once the project is created, let’s delete the existing WeatherForecast controller and model file.

Let’s create a folder in the project named

  • Model
  • Services

Right-click on Solution -> Add-> New Folder

Creating a Model

Right-click on Model Folder and select Add then click on New Item then enter class Name (Department.cs) and press the Add button.

namespace dotNet8CRUDWebAPI.Model
{
    public class Department
    {

        public int Id { get; set; }
        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

For Adding and updating the department list create another model AddUpdatedepartment.cs

namespace dotNet8CRUDWebAPI.Model
{
    public class AddUpdateDepartment
    {

        public required string DepartmentName { get; set; }
        public string Description { get; set; } = string.Empty;
        public bool IsActive { get; set; } = true;
    }
}

Create Services

Create an interface, Right click on Services Folder select Add, and click on New Item then select an interface and enter Interface Name(IDepartment.cs), and press the Add button.

In the interface, we are going to define business logic.

using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public interface IDepartment
    {
        List<Department> GetAllList(bool? IsActive);
        Department? GetById(int id);
        Department AddDeparement(AddUpdateDepartment DeptObj);
        Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj);
        bool DeleteDepartmentById(int id);

    }
}

Create a concrete class, Right click on Services Folder and select Add, and click on New Item then select the class and enter class Name(DepartmentServices.cs) and press the Add button.

In the concrete class, we are going to implement the interface.


using dotNet8CRUDWebAPI.Model;

namespace dotNet8CRUDWebAPI.Services
{
    public class DepartmentServices : IDepartment
    {
        private readonly List<Department> _departmentList;

        public DepartmentServices()
        {
            _departmentList = new List<Department>()
            {
                new Department()
                {
                    Id = 1,
                    DepartmentName= "Computer Science",
                    Description = "Head of Department",
                    IsActive = true,


                }
            };
        }
        public List<Department> GetAllList(bool? IsActive)
        {
            return IsActive== null ? _departmentList : _departmentList.Where(dept=>dept.IsActive==IsActive).ToList();
        }

        public Department? GetById(int id)
        {
            return _departmentList.FirstOrDefault(dept=>dept.Id==id);
         }


        public Department AddDeparement(AddUpdateDepartment DeptObj)
        {
            var AddDepartment = new Department()
            {
                Id = _departmentList.Max(id=> id.Id) + 1,
                DepartmentName = DeptObj.DepartmentName,
                Description = DeptObj.Description,
                IsActive =DeptObj.IsActive
            };
            _departmentList.Add(AddDepartment);

            return AddDepartment;
        }
              
        
        
        public Department? UpdateDepartment(int id, AddUpdateDepartment DeptObj)
        {
            var Deptindex = _departmentList.FindIndex(idx => idx.Id==id);

            if(Deptindex>0)
            {
                var Dept = _departmentList[Deptindex];
                Dept.DepartmentName = DeptObj.DepartmentName;
                Dept.Description = DeptObj.Description;
                Dept.IsActive = DeptObj.IsActive;

                _departmentList[Deptindex] = Dept;

                return Dept;

            }
            else
            {
                return null;
            }

        }

        public bool DeleteDepartmentById(int id)
        {
            var deptindex = _departmentList.FindIndex(idx => idx.Id == id);
            if (deptindex>0)
            {
                _departmentList.RemoveAt(deptindex);
            }
            return deptindex>0;
        }

    }
}

Creating a  Controller

Create a Controller, Right-click on Controller Folder select Add -> Controller -> API -> API Controller, and enter controller Name (DepartmentController.cs) and press the Add button.

  • Open the DepartmentController file
  • Create a constructor and inject the IDepartment interface
  • Create action methods
    • GET
    • POST
    • PUT
    • Delete
using dotNet8CRUDWebAPI.Model;
using dotNet8CRUDWebAPI.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotNet8CRUDWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DepartmentController : ControllerBase
    {
        private readonly IDepartment _department;

        public DepartmentController(IDepartment department)
        {
           _department = department;
        }

        [HttpGet]
        public IActionResult Get([FromQuery] bool? isActive=null)
        {
            return Ok(_department.GetAllList(isActive));
        }
        [HttpGet]
        [Route("{id}")]
        public  IActionResult Get(int id)
        {
            var dept = _department.GetById(id);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(dept);

        }

        [HttpPost]
        public IActionResult Post(AddUpdateDepartment obj)
        {
            var dept = _department.AddDeparement(obj);
            if(dept == null)
            {
                return BadRequest();
            }
            return Ok(new
            {
                message = "Deparment Created Successfully...!",
                id = dept!.Id
            });
        }

        [HttpPut]
        [Route("{id}")]
        public IActionResult Put([FromRoute] int id, [FromBody]  AddUpdateDepartment obj)
        {
            var dept = _department.UpdateDepartment(id, obj);
            if (dept == null)
            {
                return NotFound();
            }
            return Ok(new
            {
                message = "Deparement Updated Successfully...!",
                id = dept!.Id
            });
        }

        [HttpDelete]
        [Route("{id}")]
        public IActionResult Delete([FromRoute]int id)
        {
            
            if (!_department.DeleteDepartmentById(id))
            {
                return NotFound();
            }
            return Ok(new {
                message = "Department Deleted Successfully..!",
                id = id
            });
        }
    }
}

Register services

Open the Program.cs file and register IDepartment and DepartmentServices as an AddSingleton.

using dotNet8CRUDWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddSingleton<IDepartment,DepartmentServices>();
var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Run the API Project

Get All Department List

Adding a Deparments

.NET 8: ASP.Net Core Web API CRUD Operations

Updating Department

.NET 8: ASP.Net Core Web API CRUD Operations

Delete a Department

.NET 8: ASP.Net Core Web API CRUD Operations

See More: How to Avoid Data Overload in EF Core

The post .NET 8: ASP.Net Core Web API CRUD Operations appeared first on Tech Insights.

]]>
https://reactconf.org/net-8-asp-net-core-web-api-crud-operations/feed/ 1 245