MVC app with login authentication in ASP.NET Core

2 minute read

Introduction

Overview

In Previous article, I created a web application that displays the development environment construction and Hello World of ASP.NET Core.
This time I would like to develop an MVC application using ASP.NET Core.

Scope of this article

  • ASP.NET Core MVC app development
  • SQLite integration
  • User account authentication

ASP.NET Core MVC App Development

Project creation

    1. Open Visual Studio
  1. Select Create New Project
    1.png
    1. Select ASP.NET Core Web Application
      2.png
  2. Enter an arbitrary project name and select [Create]
    3.png
  3. Select [Change] for the authentication item
    a.png
  4. Select [Individual User Account] / [In-App Store User Account] / [OK]
    5.png
  5. Select [Web Application (Model View Controller)] / [Create]
    a - コピー.png

    Install SQLite solution

    1. Open [Visual Studio]-[Tools]-[NuGet Package Manager]-[Manage NuGet Packages for Solution]
  6. Select Microsoft.EntityFrameworkCore.Sqlite
    1. Select the project to install
  7. Select [Install]
    13.png

    Ready to use SQLite

    1. Change the following part of Startup.cs

Before


services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

After


services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
  1. Change the following part of appsettings.json that manages connection information to DB

Before


"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-Delete2-9D2AC501-24A9-42B7-9482-DB0EC43700ED;Trusted_Connection=True;MultipleActiveResultSets=true"

After


"DefaultConnection": "Data Source=sample.db"
    1. Open [Visual Studio]-[Tools]-[NuGet Package Manager]-[Package Manager Console]
  1. Execute the following two commands
    PM> Add-Migration Initial
    PM> Update-Database

Creating a controller

    1. Select [Controller Right Click]-[Add]-[Controller]
      スクリーンショット (8).png
  1. Select [MVC Controller / Empty] / [Add]
    6.png
    1. Select [Controller Class-Empty]
  2. Name it [SampleController.cs]
  3. Select [Add]
    7.png
  4. This time, we will create two screens, AuthNotRequired, which can be opened without logging in, and AuthRequired, which requires login. Therefore, each method that returns two screens is defined in SampleController.

SampleController.cs


using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace SampleApp.Controllers
{
    public class SampleController : Controller
    {
        // [AllowAnonymous]If you give, you do not need to log in
        [AllowAnonymous]
        public IActionResult AuthNotRequired()
        {
            ViewData["Message"] = "This page does not require login.";
            return View();
        }

        // [Authorize]You will need to log in if you grant
        [Authorize]
        public IActionResult AuthRequired()
        {
            ViewData["Message"] = "This page requires login.";
            return View();
        }
    }
}

Create view

    1. To create a folder to store the screen files, right-click the [Views] folder and select [Add]-[New Folder]. This time, create a Sample folder temporarily.
      スクリーンショット (9).png
  1. Right-click the [Sample] folder and select [Add]-[View] to create a screen file.
    Create AuthNotRequired.cshtml and AuthRequired.cshtml to create two screens as described above.
    スクリーンショット (10).png

    1. Create the source of the screen that does not require login.
      The message was stored in the variable ViewData [“Message”] when the controller was created, but it can be displayed on the screen by writing as follows.

AuthNotRequired.cshtml


<div class="text-center">
    <h1>@ViewData["Message"]</h1>
</div>
  1. Create the source of the screen that requires login.
    The description on one line is using in C #, and login information can be handled by reading this model.
    Therefore, login information can be displayed with a short description such as @ (User.Identity.Name) as in the 5th line.

AuthRequired.cshtml


@model Microsoft.AspNetCore.Identity.UI.V4.Pages.Account.Manage.Internal.IndexModel

<div class="text-center">
    <h1>@ViewData["Message"]</h1>
    <h1>Email address:@(User.Identity.Name)</h1>
</div>

in conclusion

Let’s actually move it.
Press the execute button and try to access the login-free screen localhost: 44380 / Sample / AuthNotRequired.
If the message described in the source is displayed as shown in the image below, it is successful.
8.png
Next, try accessing the screen that requires login localhost: 44380 / Sample / AuthRequired. Since you are not logged in, you are successful if you are skipped to the login screen.
Select Register as a new user to create an account.
9 - コピー.png
Enter your email and password and select Register.
10.png
Select [Click here to confirm your account] to confirm the address.
11_.png
Log in with the account you created last, and try accessing localhost: 44380 / Sample / AuthRequired on the screen that requires you to log in again.
If the message described in the source and the registered e-mail address are displayed without being skipped to the login screen, it is successful.
15_.png