Authentication Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Thu, 04 Jan 2024 07:06:40 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 Authentication Archives - Tech Insights 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
How to Create CRUD API in Django Rest Framework https://reactconf.org/how-to-create-crud-api-in-django-rest-framework/ https://reactconf.org/how-to-create-crud-api-in-django-rest-framework/#respond Tue, 18 Apr 2023 02:45:06 +0000 https://labpys.com/?p=1081 Web development has become a crucial component of enterprises in the modern world. To build an effective web application, we need to create a robust API. The Django Rest Framework …

The post How to Create CRUD API in Django Rest Framework appeared first on Tech Insights.

]]>
Web development has become a crucial component of enterprises in the modern world. To build an effective web application, we need to create a robust API.

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

Django CRUD (Create, Read, Update, Delete) Operation

Before we start building the CRUD API, we need to install Django and  Django Rest Framework. The steps are as follows.

Setting Django Rest Framework

Install Django and Rest Framework

Pip install Django
Pip install djangorestframework

Create a new Django Project

Django-admin startproject CRUD_API_Restframework

Create a new App

Python manage.py startapp CRUD_API

Configure the Settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CRUD_API',
    'rest_framework',
]

Create Django Models

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

Migration

Python manage.py makemigrations
Python manage.py migrate

Create Serializers

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()

Create a Views

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)
 
 

Create URLS

We need to map the views to URLs to make them accessible through the API. Here are the steps to follow.

  • Create a new file urls.py in the CRUD_API directory

Configure the URLs for the views

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"),
]

Include the app Urls in the project URLs

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('CRUD_API.urls')),
]

Start the Django Development Server

Python manage.py runserver

Testing the API using POSTMAN

Here can test the API using the POSTMAN tool.

Create User

Get All Users

Get By Id

Update User

Delete User

The post How to Create CRUD API in Django Rest Framework appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-crud-api-in-django-rest-framework/feed/ 0 1081