Skip to content

RazorPageTraining/Part_3_Identity

Repository files navigation

Identity

  • On this project, we gonna use Code First Process. What is Code First? In a simple term, we create a project with entity model, and the Entity Framework API will create the database based on your entity classes and configuration when we do a Migrations.
  • Source code inside this repository is a completed source code of what you gonna do.
  • You can refer this source code when you develop your project.
  • What is Identity?
  • What is Migrations?

NO. TITLE
1 Introduction
2 Installation
3 Net 5 CRUD (Example ONLY)
4 How to run this project
5 How to create RazorPage project
6 Packages
7 Create Database
8 Create Identity
9 Create Entity Models
10 Setup DB connection on project
11 Database Migration
12 Change calling
13 Test login
14 Other Resources
15 References


How to run this project

  1. Download this project and open your terminal or VS Code.

  2. On your terminal type this command, but first you need to make sure you know where your project folder is. For my case, I put it on my desktop

    image

    code -r TrainingRazor

    image

  3. "TrainingRazor" name on this command is the folder name of the project. The name is depends on you.

  4. System will open the project on your Code Editor.

  5. Other than that, by using VS Code, you can just drag project folder on VS Code and and trust the author.

  6. If VS Code authorize you to insert some assets, just click Yes/Accept

  7. Back to Menu



How to create RazorPage project

  1. Open your installed VS Code and open VS Code terminal or any terminal that you have.

  2. Change to the directory (cd) which will contain the project.

    cd desktop

    image

  3. Run the following commands :

    dotnet new webapp -o TrainingRazor -au individual        

    image

  4. "TrainingRazor" is the projects name. Name depends on you.

  5. After you finish create the project, you can type this commands on terminal to start code :

    code TrainingRazor

    image

  6. After VS Code appear, it will show like this on VS Code.

    image

  7. Click Yes on this :

    image

  8. You need to trust the HTTPS development certificate by running the following command on the project terminal:

    • open Terminal on VS Code Menu:

    image


    • After you click "New Terminal" Terminal will appear on bottom:

    image


    - Type this console command on Terminal:
    dotnet dev-certs https --trust

    image


  9. If you already has a valid HTTP Certificate like below image, you can skip no 10 and no 11.

    image

  10. The preceding command doesn't work on Linux. See your Linux distribution's documentation for trusting a certificate. The preceding command displays the following dialog, provided the certificate was not previously trusted :

    image

  11. Select Yes if you agree to trust the development certificate.

  12. Back to Menu


Packages

  1. For this project we gonna use 2 package that we need to install. On your terminal inside VS Code, you need to type this commands and click enter or just copy & paste :

    dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design --version 6.0.5
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 6.0.5

    image

  2. After this package has been installed, you can open your TrainingRazor.csproj and see whether those 2 package has been installed.

    image

  3. Run your project to see whether there are errors. If there are errors, remove the package and install it back or install with different version on Nuget Gallery website as no 4. You can skip no 4 and no 5 if you already succeed.

  4. You can find the package on search bar (Skip this if you already succeed):

    image

  5. Always click on the first link and you can view all the package version.

    image

  6. Back to menu


Create Database

  1. Before we start to code, you need to create a database (DB).

  2. You just need to create DB using SSMS that we install earlier.

  3. Open your SSMS and create a new DB. (How to use SSMS)

    image

  4. You will get your result like this after you finished create your DB

    image

  5. Back to Menu


Create Identity

  1. If your project already run, stop the project first by click the stop button :

    image

  2. To create identity page on RazorPage, you can type this command on your project terminal via VS Code and click enter :

    dotnet aspnet-codegenerator identity

    image

  3. After the command has build succesfully, you can see on your project that you have new folder such as Areas/Identity like this :

    image

  4. Delete folder Data ONLY inside Areas/Identity

    image

  5. Open Program.cs, and delete EXACT CODE AS FOLLOWS (Use exist folder Data):

    using TrainingRazor.Areas.Identity.Data;

    image


    var connectionString = builder.Configuration.GetConnectionString("TrainingRazorIdentityDbContextConnection") ?? throw new 
     InvalidOperationException("Connection string 'TrainingRazorIdentityDbContextConnection' not found.");
    
    builder.Services.AddDbContext<TrainingRazorIdentityDbContext>(options =>
     options.UseSqlServer(connectionString));;
    
    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
     .AddEntityFrameworkStores<TrainingRazorIdentityDbContext>();;

    image

  6. Edit UseSqlite to UseSqlServer (REPLACE CODE) (We gonna use Sql Express (Local Database Server for Development) for Database)

    FROM :

    image


    TO :

    image

  7. Edit this (Login preferences) (REPLACE CODE) :

    FROM :

    image

    TO :

    image


    builder.Services.AddDefaultIdentity<IdentityUser>(options => 
         {
             options.SignIn.RequireConfirmedAccount = false;
             options.User.RequireUniqueEmail = true;
         }
     )
     .AddRoles<IdentityRole>()
     .AddEntityFrameworkStores<ApplicationDbContext>()
     .AddDefaultTokenProviders();
  8. Edit this (Set Web App startup folder (Need to Login before accessing inside Page)) (REPLACE CODE) :

    FROM :

    image

    TO :

    image


    builder.Services.AddRazorPages((options =>
    {
        options.Conventions.AuthorizeFolder("/");
    }));
  9. Open appsettings.json, and remove this code (Use DefaultConnection):

    "TrainingRazorIdentityDbContextConnection": "Server=(localdb)\\mssqllocaldb;Database=TrainingRazor;Trusted_Connection=True;MultipleActiveResultSets=true"
  10. Remove the comma on :

    image

  11. Will become like this :

    image

  12. Now, try run the project. If there are no errors, that is mean you have succeed. When the project is running, you should see that it will run this page first on startup.

    image

  13. Back to menu


Create Entity Models

  1. Create new folder inside TrainingRazor folder called Models :

    image

  2. Folder placing must be like this :

    image

  3. Create a new Entity Model Class inside folder Models :

    image

  4. This will popup and just insert the name that you wanted to :

    image

  5. A new file will be created inside Models folder :

    image

  6. Copy this code and paste inside the file Table.cs (Overwrite all code inside) and save it.

    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    
    using Microsoft.AspNetCore.Identity;
    
    namespace TrainingRazor.Models
    {
        public class ApplicationUser : IdentityUser
        {
            [StringLength(500)]
            public string Name { get; set; }
        }
    
        public class CustPurchased
        {
            [Key]
            public int Id { get; set; }
    
            [ForeignKey("ApplicationUser")]
            public ApplicationUser Creator { get; set; }
    
            [ForeignKey("Product")]
            public int? ProductId { get; set; }
            public int? Quantity { get; set; }
            public Product Product { get; set; }
        }
    
        public class Product
        {
            [Key]
            public int Id { get; set; }
    
            [StringLength(500)]
            public string Name { get; set; }
    
            [Column(TypeName = "decimal(18, 2)")]
            public decimal Price { get; set; }
        }
    }
  7. Back to menu


Setup DB Connection On Project

  1. We gonna use local db server that we installed before.

  2. On your project, open appsettings.json file and insert this (If your server name have slash " \ " , you need to insert double slash like this " \ " ):

    "ConnectionStrings": {
        "DefaultConnection": "Server=YOUR_SERVER_NAME; Database=YOUR_DB_NAME; Trusted_Connection=True; MultipleActiveResultSets=True;"
     }

    image

  3. Save the file.

  4. Back to Menu



Database Migration

  1. Before we create identity schema, we need to edit ApplicationDbContext.cs. This is what we call Code First and Not DB First

  2. Open ApplicationDbContext.cs inside Data folder, and paste this source code :

    Insert this. Include Package:

    using System;
    using Microsoft.AspNetCore.Identity;
    using TrainingRazor.Models;

    image


    Edit this :

    image


    Insert this. Declare variable:

    private ApplicationUser saUserAdmin { get; set; }
    private ApplicationUser saUserCustomer { get; set; }
    private IdentityRole role1 { get; set; }
    private IdentityRole role2 { get; set;}
    private IdentityUserRole<string> userAdmin { get; set; }
    private IdentityUserRole<string> userCustomer { get; set; }
    private PasswordHasher<ApplicationUser> passwordHasher { get; set; }

    image


    Insert this. Call Data from Database

    public DbSet<CustPurchased> CustPurchaseds { get; set; }
    public DbSet<Product> Products { get; set; }

    image


    Paste this code like this. Call method

    protected override void OnModelCreating(ModelBuilder builder)  
    {  
        base.OnModelCreating(builder);
        this.SeedUsers(builder);
        this.SeedProducts(builder);
    }  

    image


    Paste this code below OnModelCreating method (NOT INSIDE). Method to create user. This is just to show to create user by using Code First concept. You Can add user by Page or Registration, but, I just want to show Migrations process.

    private void SeedUsers(ModelBuilder builder)  
    {
         string saUsernameAdmin = "YOUR EMAIL";
         string saUsernameCustomer = "YOUR EMAIL";
    
         //YOU CAN ADD MORE ROLE AS YOU WANT
         role1 = new IdentityRole() 
         { 
             Id = Guid.NewGuid().ToString(), 
             Name = "SystemAdmin", 
             ConcurrencyStamp = Guid.NewGuid().ToString(), 
             NormalizedName = "SYSTEMADMIN" 
         };
    
         role2 = new IdentityRole() 
         { 
             Id = Guid.NewGuid().ToString(), 
             Name = "Customer", 
             ConcurrencyStamp = Guid.NewGuid().ToString(), 
             NormalizedName = "CUSTOMER" 
         };
    
         //ADD USER ADMIN
         saUserAdmin = new ApplicationUser()  
         {  
             Id = Guid.NewGuid().ToString(),
             UserName = saUsernameAdmin,  
             Email = saUsernameAdmin,
             NormalizedEmail = saUsernameAdmin.ToUpper(),
             NormalizedUserName = saUsernameAdmin.ToUpper(),
             Name = "System Admin",
             LockoutEnabled = false,  
             ConcurrencyStamp = Guid.NewGuid().ToString(),
             EmailConfirmed = true,
         };
    
         //ADD USER CUSTOMER
         saUserCustomer = new ApplicationUser()  
         {  
             Id = Guid.NewGuid().ToString(),
             UserName = saUsernameCustomer,  
             Email = saUsernameCustomer,
             NormalizedEmail = saUsernameCustomer.ToUpper(),
             NormalizedUserName = saUsernameCustomer.ToUpper(),
             Name = "Customer 1",
             LockoutEnabled = false,  
             ConcurrencyStamp = Guid.NewGuid().ToString(),
             EmailConfirmed = true,
         };
         
         passwordHasher = new PasswordHasher<ApplicationUser>(); 
    
         var saPwdHashed1 = passwordHasher.HashPassword(saUserAdmin, "YOUR PASSWORD");  
         saUserAdmin.PasswordHash = saPwdHashed1;
    
         var saPwdHashed2 = passwordHasher.HashPassword(saUserCustomer, "YOUR PASSWORD");  
         saUserCustomer.PasswordHash = saPwdHashed2;
         
         userAdmin = new IdentityUserRole<string>() 
         { 
             RoleId = role1.Id,
             UserId = saUserAdmin.Id
         };
    
         userCustomer = new IdentityUserRole<string>() 
         { 
             RoleId = role2.Id,
             UserId = saUserCustomer.Id
         };
    
    
         //BUT MAKE SURE ADD THE ROLE INSIDE IDENTITY ROLE LIKE THIS IF YOU WANT TO ADD MORE ROLE
         builder.Entity<IdentityRole>().HasData(role1);
         builder.Entity<IdentityRole>().HasData(role2);
         builder.Entity<ApplicationUser>().HasData(saUserAdmin);
         builder.Entity<ApplicationUser>().HasData(saUserCustomer);  
         builder.Entity<IdentityUserRole<string>>().HasData(userAdmin);
         builder.Entity<IdentityUserRole<string>>().HasData(userCustomer);
    } 

    Paste this code below SeedUsers class method (NOT INSIDE). Method to create product

    private void SeedProducts(ModelBuilder builder)  
    {
         builder.Entity<Product>().HasData( 
                 new Product() { Id = 1, Name = "Logitech MX Mouse", Price = 345.12M },
                 new Product() { Id = 2, Name = "Keycron Keyboard", Price = 295.23M },
                 new Product() { Id = 3, Name = "Razer Lapotop", Price = 7345.69M },
                 new Product() { Id = 4, Name = "Iphone 14 Pro Max", Price = 8798.12M },
                 new Product() { Id = 5, Name = "Xiaomi Ear Buds", Price = 45.46M }
             );
    }
  3. Delete all cs file inside Migrations folder.

  4. Now, we gonna create migration schema. You need to type this command on your terminal and click enter :

    dotnet ef migrations add CreateScheme

    image

  5. After the command has finished, you can see that a new file called CreateScheme created inside the Migrations folder

    image

    It's okay if you have Multiple Migrations folder, but you can also cut the migrations file scheme with cs extension and paste into Migrations folder inside Data folder and delete the Migrations folder outside Data folder if you finished cut and paste.

  6. After that, we gonna use this command for migrate Models that we created inside database :

    dotnet ef database update

    image

  7. You can see that your database has been update.

    Before :

    image


    After :

    image image


NOTE :

To drop database :

IT IS RECOMMENDED THAT YOU CREATE IDENTITY BEFORE CREATE OTHER DATABASE TABLE BECAUSE ONCE YOU USE THIS COMMAND, YOUR DATABASE WILL BE DELETED. ONLY USE THIS CODE ON DEVELOPMENT ENVIRONMENT AND NOT PRODUCTION ENVIRONMENT

dotnet ef database drop

If there is prompt, you just need to insert Y and click enter.


  1. Back to Menu


Change Calling

  1. After migrations finished, don't run the project yet.

  2. We need to change the calling IdentityUser to ApplicationUser each of every file that consist of IdenitityUser inside folder Account because we created a custom Identity entity class.

  3. On your VS Code, click icon search

    image

  4. And put this word inside the input that the placeholder are Search

    <IdentityUser>

    image

  5. As you can see, there's a lot of need to be changed.

  6. But, don't worry, you just need to put this word inside the input that the placeholder are Replace

    <ApplicationUser>

    image

  7. After that, you just click this icon.

    image

  8. Click the button Replace, and VS Code will do the replace part.

    image

  9. You will see all the file that have the word will be error, but dont worry, you just need to include this code on each and every file that has error.

    using TrainingRazor.Models;

    For example :

    image

  10. For file that have extension .cshtml , you need to put it like this :

    @using TrainingRazor.Models;

    For example :

    image

  11. If you still got a file that have error, don't worry, you can do it like this

    For example, you have a situation like this

    image

    You can just change the IdentityUser to ApplicationUser

    The Solution (No more errors because we change the variable declaration of IdentityUser to ApplicationUser) :

    image


    Another example if you have a situation like this

    image

    Just change IdentityUser to ApplicationUser like this

    image

  12. Back to Menu



Test login

  1. After finished everything, run this project by click F5 or click Run > Start Debugging

    image

  2. Your project will run on your browser

    image

  3. Insert your credentials (Login Email and Username that you set on migrations) and click the "Log in" button

  4. When you succeed to login, you will be brought to this page.

    image

  5. Back to Menu



References

  1. https://www.tektutorialshub.com/asp-net-core/asp-net-core-identity-tutorial/
  2. https://blog.francium.tech/asp-net-core-basic-authentication-authorization-in-razor-pages-with-postgresql-b1f2888b21d0
  3. https://www.learnrazorpages.com/identity/customising-identity
  4. https://www.learnrazorpages.com/identity
  5. Back to Menu

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks