CsitLabs
  • CSIT Labs
  • 1st Semester
    • Digital Logics
      • Lab 1
      • Lab 2
      • Lab 3
      • Lab 4
      • Lab 5
      • Lab6
    • IIT
    • Physics Lab Report Formet
  • 2nd Semester
    • Algorithms used in Discrete Structure class
    • Microprocessor
      • 8085 Microprocessor
        • Arithmetic and Logical Instruction Set
        • Branching Instruction Set
        • Data Transfer and Instruction Set
        • Multiply, Divide and Memory Block Operations
        • Rotate Instruction Set
        • Subroutine, Stack and BCD Conversion](Subroutine_Stack_BCD_Conversion
      • 8086 Microprocessor
        • Basic Arithmetic
        • Practice Programs for 8086 Microprocessor
        • String Processing
    • Object Oriented Programming using C++
      • File Access Pointers
      • Standard Exceptions in C++
    • Statistics-I
  • 3rd Semester
    • Computer Architecture
      • Practical labs
    • Computer Graphics
      • Practial
      • Simulation of Two Dimensional Transformation
      • Scan Conversion Algorithm
    • Data Structures and Algorithms
      • Array methods (Introduction)
      • Stack
      • Queue
      • Recursion
      • Linked List
      • Sorting Algorithms
      • Searching and Hashing Algorithms
      • Trees and Graphs
      • Lab practice
    • Numerical Method Labs
      • Lab practice
    • Statistics-II Labs
      • Confidence interval of mean assuming normal distribution
      • One Sample T test
      • Two Sample T test
      • Regression Analysis
      • Two Sample T test
      • Design_of_Experiment
        • CRD (Completely Randomized Design)
        • RBD (Randomized Block Design)
        • RBD (Randomized Block Design)
      • Non-parametric_test
        • Binomial Test
        • Cochran Q test
        • Kolmogorov-Smirnov one sample test
        • Run test
        • Friedman-F_test
          • Friedman F test
          • Friedman F test
        • Kruskal-Wallis-H_test
          • Kruskal Wallis H test
          • Kruskal Wallis H test
        • Mann-Whitney-U_test
          • Mann Whitney U test
          • Mann Whitney U test
        • Median_test
          • Median Test
          • Median Test
        • Wilcoxon-Matched-pair_signed_rank_test
          • Wilcoxon Matched pair signed rank test
          • Wilcoxon Matched pair signed rank test
  • 4th Semester
    • Artificial Intelligence
    • Computer Networks
      • Networking commands in CMD
    • DBMS Lab
    • Operating System
      • Linux Commands
    • Theory of Computation
      • Lab 1 (DFA)
      • Lab 2 (NFA)
  • 5th Semester
    • Cryptography
    • Design and Analysis of algorithms
    • Multimedia
      • Animation Creation with Blender
      • FL Studio - Simple Effect Creation
      • Macromedia FreeHand - Logo Creation
      • Audio Mixing
      • Adobe Photoshop - ID Card Creation
      • Video Editing with Adobe Premiere Pro
    • Simulation & Modeling
      • Lab 1: Random Number Generation
    • System Analysis and Design
    • Web Technology
      • Lab Assignment – I (HTML)
      • Lab Assignment – II (CSS)
      • Lab Assignment – III (JavaScript and XML)
      • Lab Assignment – IV (PHP)
      • Web Technology
        • php
          • Database connection using PHP and MySQL
          • Login form
          • Login form
  • 6th Semester
    • Compiler Design and Construction
    • NET Centric Computing
      • Class Codes
        • Authentication and Authorization in ASP.NET
        • C# Basics
      • Lab Codes
        • Practical 1
        • Practical 2
          • Number Operations Web App
          • User Registration Form
          • User Registration Console App
        • Practical 3
          • Authentication and Authorization (Claims, Roles and Policies)
          • Client side state management in ASP.NET
          • Entity Framework Core
          • Form Validation
            • React form validation
          • HTML Tag Helpers
          • MVC demonstration
          • Razor Syntax
          • Server Side State Management in ASP.NET
      • Self Projects
        • Do while programs
        • Role playing game battle challenge
        • Project overview
        • Authentication
          • wwwroot
            • lib
              • jquery-validation
                • The MIT License (MIT)
  • 7th Semester
    • Advanced Java Programming
      • Class Codes
        • Unit1-6&8
          • javafx-sdk-21.0.1
            • legal
              • javafx.graphics
                • Independent JPEG Group (IJG) JPEG v9e
                • Mesa 3-D Graphics Library v21.0.3
              • javafx.media
                • Microsoft DirectShow Samples v156905
                • GNU Glib v2.72.0
                • GStreamer v1.20.1
                • LibFFI v3.4.4
              • javafx.web
                • IBM International Components for Unicode (ICU4C) v73.1
                • xmlsoft.org: libxml2 v2.10.4
                • xmlsoft.org: libxslt v1.1.35
                • WebKit Open Source Project: WebKit v616.1
          • src
            • main
              • java
                • Unit 1: Programming in Java
                  • 2. Concepts and Topics
                • Unit 2: User Interface Components with Swing
                • Unit 3: Event Handling
                • Unit 4: Database Connectivity
                • Unit 5: Network Programming
                • Unit 6: GUI with JavaFX
        • Unit7
          • src
            • main
              • webapp
                • index
      • Lab Codes
        • Lab
          • src
            • main
              • java
                • Practical 1
                • Practical 2
                • Practical 3
                • Practical 4
                • Practical5
    • Data warehouse and Data mining
  • docs
    • Contributor Covenant Code of Conduct
Powered by GitBook
On this page
  • Steps to add Authentication and Authorization in ASP.NET Core
  • 1. Using Username and Password only (no roles)
  • 2. Using Roles

Was this helpful?

  1. 6th Semester
  2. NET Centric Computing
  3. Class Codes

Authentication and Authorization in ASP.NET

PreviousClass CodesNextC# Basics

Last updated 8 months ago

Was this helpful?

  • Authentication is the process of verifying the identity of a user.

  • Authorization is the process of verifying that the user has the necessary permissions to access the resources.

  • We need to be Authenticated to access Authorization

  • We can have cookies and session authentication.

Steps to add Authentication and Authorization in ASP.NET Core

1. Using Username and Password only (no roles)

  1. At first, we need to configure the file.

    • In the headers, add the following lines:

      using Microsoft.AspNetCore.Authentication; // to add authentication
      using Microsoft.AspNetCore.Authentication.Cookies; // to add cookie
      using Microsoft.AspNetCore.Authorization; // to add authorization
      using System.Security.Claims; // to add claims -> claims are the authorization details
      • This will add the necessary libraries to the file. The Claims are the authorization details.

    • Let's say that the Privacy page is only accessible to authenticated users. So, in the class HomeController, after the Index method, let's add the [Authorize] attribute to the Privacy method.

      [Authorize]
      public IActionResult Privacy()
      {
          return View();
      }
      • This will make the page accessible only to authenticated users.

    • Now, let's add the login method to the HomeController class as the authentication form and the logic to authenticate the user is needed.

      /**
      * This is the get method for login
      * It will take return url and send it to the view
      */
      [HttpGet]
      public IActionResult Login(string ReturnUrl)
      {
          // take return url to view for this use ViewData
          ViewData["returnURL"] = ReturnUrl;
          return View();
      }
      • This will take the return URL and send it to the view.

      • The return URL is the URL to which the user will be redirected after the login.

      • The view will render the login form and authenticate the user, then redirect the user to the return URL.

    • Now, let's add the post method for the login. This will take the username and password and return to the return URL.

      /**
      * This is the post method for login
      * It will take username and password and return to the return url
      */
      [HttpPost]
      public IActionResult Login(string username, string password, string ReturnUrl)
      {
          if (username == "ram" && password == "ram")
          {
              // add authroization
              // claim: authorization detail
              // identity: which mechanism to be used for authorization:cookie
              // principal: who is authorized
              List<Claim> claims = new List<Claim>();
              claims.Add(new Claim(ClaimTypes.NameIdentifier, username));
              claims.Add(new Claim(ClaimTypes.Name, username));
              // identity->claims
              ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
              // principal->identity
              ClaimsPrincipal principal = new ClaimsPrincipal(identity);
              // executing->sign in
              HttpContext.SignInAsync(principal); //execute
              return Redirect(ReturnUrl);
          }
          return View();
      }

      In this method:

      • We are checking if the username and password are correct.

      • If they are, we are creating a list of claims. A claim is an authorization detail. We are adding the username, name, and role to the claims.

      • Then, we are creating an identity with the claims and the cookie authentication scheme. An identity is the mechanism to be used for authorization. Here, we are using the cookie.

      • Then, we are creating a principal with the identity. Principal is the one who is authorized.

      • Finally, we are signing in the principal. This will authenticate the user.

    • Now, create a Login.cshtml file in the folder for the authentication form.

      @* create login form and also extract return url *@ @{ ViewData["Title"]
      ="Login"; } @{ string retUrl = ViewData["returnURL"] as string; }
      <form
        method="post"
        action="Login?ReturnUrl=@System.Net.WebUtility.UrlEncode(retUrl)"
      >
        <label>Username</label>
        <input type="text" name="username" /><br />
        <label>Password</label>
        <input type="text" name="password" /><br />
        <input type="submit" name="submit" value="login" />
      </form>
      • Here, the main thing is the action="Login?ReturnUrl=@System.Net.WebUtility.UrlEncode(retUrl)".

      • This will take the return URL and send it to the Login method.

      • The UrlEncode method will encode the URL. This is necessary because the URL may contain special characters that may break the URL.

      • The form will take the username and password and submit it to the Login method.

  2. Then, in :

    // to add cookie authentication
    using Microsoft.AspNetCore.Authentication.Cookies;
    
    // adding authentication through cookie
    // after adding cookie, login path must be /Home/Login
    builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options => options.LoginPath = "/Home/Login");
    • This will add the cookie authentication to the application.

    • The login path must be /Home/Login.

2. Using Roles

The roles are the permissions that the user has. We can add roles to the user and check if the user has the necessary roles to access the resources.

The process of adding roles is similar to adding claims. We need to add the roles to the claims and then add the claims to the identity.

  1. Let's say that we have a role called Student. We can add this role to the claims. In the Login method in the HomeController class, add the role to the claims.

    if (username == "ram" && password == "ram")
    {
        // add authroization
        // claim: authorization detail
        // identity: which mechanism to be used for authorization:cookie
        // principal: who is authorized
        List<Claim> claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.NameIdentifier, username));
        claims.Add(new Claim(ClaimTypes.Name, username));
        /** adding role **/
        claims.Add(new Claim(ClaimTypes.Role, "Student")); // adding role
        // identity->claims
        ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        // principal->identity
        ClaimsPrincipal principal = new ClaimsPrincipal(identity);
        // executing->sign in
        HttpContext.SignInAsync(principal); //execute
        return Redirect(ReturnUrl);
    }
    • Here, we are adding the role Student to the claims.

  2. Now, let's say that the Dashboard page is only accessible to the users with the role Student. We can add the [Authorize(Roles = "Student")] attribute to the Dashboard method in the HomeController class.

    [Authorize(Roles = "Student")]
    public IActionResult Dashboard()
    {
        return View();
    }
    • This will make the page accessible only to the users with the role Student.

    • This will be the dashboard page that will be accessible only to the users with the role Student.

Then, create a Dashboard.cshtml file in the folder.

Controllers/HomeController.cs
Views/Home
Program.cs
Views/Home