ASP.NET Core Identity self-study record (.NET FrameworkCore3.0) Day 1

2 minute read

This self-study goal

  • Add authentication with ASP.NET Core Identity to web pages created with MVC.NET Core unauthenticated template
  • Use Postgres as a storage area
  • Add custom fields to user information
  • Add various Roles to user information
  • In addition, you can play around with it and learn how to use it to some extent that you will use it in your business.

I’m thinking of going like this.
I don’t have much knowledge, so if you make a mistake, please dig in …

1. 1. Create a product that can be certified at a minimum

1-1. Create a plain MVC.NET Core

  • I don’t think you need to explain here,
    New Project in VS2019> Select ASP.NET Core Web Application
    The settings on the next screen look like this
    mojikyo45_640-2.gif
  • Basically, it is a work to get closer to the template created with authentication.

1-2. Reference package

 Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore
 Microsoft.AspNetCore.Identity.EntityFrameworkCore
 Microsoft.AspNetCore.Identity.UI
 Microsoft.EntityFrameworkCore
 Npgsql.EntityFrameworkCore.PostgreSQL
 Microsoft.EntityFrameworkCore.Tools

1-3. Add DBContext

Create TestApplicationDbContext.cs to create an EF class that inherits the Identity class

TestApplicationDbContext.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace WebTeqKensho.Data
{
    public class TestApplicationDbContext : IdentityDbContext
    {
        public TestApplicationDbContext(DbContextOptions<TestApplicationDbContext> options)
    : base(options)
        {
        }
    }
}

Create _LoginPartial.cshtml to create a template for login links

_LoginPartial.cshtml


@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

<ul class="navbar-nav">
    @if (SignInManager.IsSignedIn(User))
    {
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index" title="Manage">Hello @User.Identity.Name!</a>
        </li>
        <li class="nav-item">
            <form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
                <button type="submit" class="nav-link btn btn-link text-dark">Logout</button>
            </form>
        </li>
    }
    else
    {
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a>
        </li>
        <li class="nav-item">
            <a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Login</a>
        </li>
    }
</ul>

Added login template loading to standard template (added to line 20 of _Layout.cshtml)

_Layout.cshtml


<partial name="_LoginPartial" />

1-5. Startup.cs settings

Add processing to Configure Services

Startup.cs


        public void ConfigureServices(IServiceCollection services)
        {
            //Entity Framework connection settings
            services.AddDbContext<TestApplicationDbContext>(options =>
                options.UseNpgsql(
                Configuration.GetConnectionString("DefaultConnection")));
            //Associate Identity and connection
            services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<TestApplicationDbContext>();
            services.AddControllersWithViews(); //Existing
        }

Add processing to Configure

Startup.cs


            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseAuthentication();      //Added for authentication
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();   //Loading page transition settings for authentication
            });

1-6. Add connection information to appsettings.json

  • Connection information is different for each person, so please change it appropriately.

appsettings.json


  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Port=5432;User Id=tester;Password=tester;Database=testDB"
  },

1-7. Migrate and add table to DB

Create update file (executed in the package manager console)

Add-Migration firstIdentity

Run

Update-Database -Verbose

This completes the preparations for authenticating using at least identity.
From the next time, we will focus on customization.