The post Implement JWT Authentication and Authorization in ASP.NET Core appeared first on Tech Insights.
]]>Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project
Add the “Microsoft.AspNetCore.Authentication.JwtBearer” NuGet package to your project.
Another way to install the package “Microsoft.AspNetCore.Authentication.JwtBearer” via Package Manager Console
PM> Install-Package Microsoft.AspNetCore.Authentication.JwtBearer
Add the following information in the appettings.json file.
"JWT": {
"key": "YouSecreteKeyforAuthenticationtovalidateApplication",
"Issuer": "reactconf.org",
"Audience": "reactconf.org"
},
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();
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; }
}
}
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");
}
}
}
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.
]]>The post How to Create CRUD API in Django Rest Framework appeared first on Tech Insights.
]]>The Django Rest Framework (DRF) is a powerful tool to create CRUD API in the Django web framework, which is based on python
In this post, we will look at how to create CRUD API in the Django Rest Framework. Create, Retrieve, Update, and Delete are the four fundamental activities you may do using a CRUD API. To interface with a database, web applications frequently use these operations.
Also, Check the Previous Article Implement Join Operations in Django ORM
Before we start building the CRUD API, we need to install Django and Django Rest Framework. The steps are as follows.
Pip install Django Pip install djangorestframework
Django-admin startproject CRUD_API_Restframework
Python manage.py startapp CRUD_API
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'CRUD_API', 'rest_framework', ]
Now we need to create a Models in our app. The model will define the structure of data.
from django.db import models # Create your models here. class authentication(models.Model): username = models.CharField(max_length=100) password = models.CharField(max_length=100) emailid = models.CharField(max_length=100,default=True) is_active = models.IntegerField() firstname = models.CharField(max_length=100,default=True) lastname = models.CharField(max_length=100,default=True) address = models.CharField(max_length=100,default=True) contactno = models.CharField(max_length=100,default=True) gender = models.CharField(max_length=100,default=True) def __str__(self): return self.username
Python manage.py makemigrations Python manage.py migrate
Serializers create a format for complicated data types, like Python objects, so that it may be quickly translated into JSON or XML content. Models in DRF are transformed into JSON, XML, or other content types using serializers.
from rest_framework import serializers from .models import authentication class serialize(serializers.ModelSerializer): class Meta: model = authentication fields =['id','username','password','emailid'] class messagserializer(serializers.Serializer): Response = serializers.CharField() Message = serializers.CharField()
The API’s fundamental component views, respond to queries, process data, and handle incoming request. Django Rest Framework has a number of views that can be customized to support CRUD activities
from django.shortcuts import get_object_or_404, redirect, render from django.template.response import TemplateResponse from django.http import HttpResponse,HttpRequest from rest_framework import serializers,status from rest_framework.response import Response from rest_framework.decorators import api_view from django.urls import reverse from django.contrib import messages from django.contrib.auth import authenticate from .models import authentication from .Serializers import serialize,messagserializer import json import requests # Create your views here. @api_view(['GET',]) def getusers(request): if request.method == 'GET': getusers = authentication.objects.all() serializer = serialize(getusers, many=True) request.session['users'] = serializer.data return Response(serializer.data) @api_view(['GET']) def getusersid(request): if request.method == 'GET': argdata = request.data getuserss = authentication.objects.filter(username=argdata['username'] , password=argdata['password']) serializer = serialize(getuserss, many=True) request.session['users'] =serializer.data return Response(serializer.data) return Response('Failure') @api_view(['POST',]) def postusers(request, *args, **kwargs): argdata = request.data if request.method == 'POST': argdata = request.data isvalid = authentication.objects.filter(username=argdata['username']).exists() if isvalid==False: postusers = authentication.objects.create(username=argdata['username'],password=argdata['password'],emailid=argdata['emailid'],is_active=1) postusers.save() getuserss = authentication.objects.filter(username=argdata['username']) serializer = serialize(getuserss, many=True) context = {"getdata":serializer.data,"response":"Success"} return Response(context) else: context = [{"Response":'User Already Registered',"Message":'403'}] serializer = messagserializer(context, many=True) return Response(serializer.data) @api_view(['PUT','GET']) def Editusers(request, *args, **kwargs): if request.method == 'PUT': user_instance = authentication.objects.get(username=request.data.get('username')) #self.get_object(id,request.data.id) if not user_instance: return Response({"message":'User Not Registered'},status=status.HTTP_404_NOT_FOUND) data = { 'username': request.data.get('username'), 'password': request.data.get('password'), 'emailid': request.data.get('emailid'), 'is_active': request.data.get('is_active') } serializer = serialize(instance=user_instance, data=data,partial=True) if serializer.is_valid(): serializer.save() context = {"getdata":serializer.data,"response":"Success"} return Response(context) return Response(serializer._errors,status=status.HTTP_400_BAD_REQUEST) @api_view(['DELETE']) def Delete_User(request): argdata = request.data isvalid = authentication.objects.filter(username=argdata['username']).exists() if isvalid==True: users = get_object_or_404(authentication,username=argdata['username']) users.delete() context = {"response":"Success"} return Response(context) else: context = [{"Response":'User Not Registered',"Message":'403'}] return Response(context)
We need to map the views to URLs to make them accessible through the API. Here are the steps to follow.
from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('getusers/',views.getusers, name="getusers"), path('getusersid/',views.getusersid, name="GetUseById"), path('Addusers/',views.postusers, name="postusers"), path('Editusers/',views.Editusers, name="Editusers"), path('Delete_User/',views.Delete_User, name="Delete_User"), ]
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('CRUD_API.urls')), ]
Python manage.py runserver
Here can test the API using the POSTMAN tool.
The post How to Create CRUD API in Django Rest Framework appeared first on Tech Insights.
]]>