set login page as default in asp.net core mvc Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Fri, 09 Dec 2022 17:51:03 +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 set login page as default in asp.net core mvc Archives - Tech Insights 32 32 230003556 How to create Login Page using Asp.net Core MVC C# With Database https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/ https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/#comments Fri, 09 Dec 2022 17:51:03 +0000 https://labpys.com/?p=481 Authentication is mandatory for security in any type of application. One of the fundamental requirements for an application is a login page, which is why many application development processes begin …

The post How to create Login Page using Asp.net Core MVC C# With Database appeared first on Tech Insights.

]]>
Authentication is mandatory for security in any type of application. One of the fundamental requirements for an application is a login page, which is why many application development processes begin with implementing an authentication module. In this article, we’ll learn how to create login page using asp.net core MVC C# With Database.

Pre-requisite

  • NET Core SDK from here
  • Visual Studio or Visual Studio Code from here
  • SQL Server database from here

Create an ASP.NET Core MVC Project

Go to the File menu and click on New and select Project. In the new project window, select ASP.NET Core Web App(Model-View-Controller).

Document

More Related Article

Then set the project location and project name.

Install NuGet package

Once the new project is created install NuGet Packages for that right click on Solution and select Manage NuGet Packages for the solution  

  • Microsoft Entity Framework Core SQL Server
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

The connection string “connectionstr” is saved in appSettings.json , you can change it as per your need

"ConnectionStrings": {
    "connectionstr": "Server=(local)\\MSSQL;Database=Login_Auth;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

Create Model

Creating a model is an essential step in developing an ASP.NET Core application. A model is a representation of the data that our application will use and manipulate. By creating a model, we define the structure of the data and its relationships with other models. This allows us to easily work with data in our application and perform CRUD (Create, Read, Update, Delete) operations on it

using System.ComponentModel.DataAnnotations;
namespace Auth_Login.Models
{
    public class UserLogin
    {
        [Key]
        public int id { get; set; }

        [Required(ErrorMessage ="Please Enter Username")]
        [Display(Name = "Please Enter Username")]
        public string UserName { get; set; }

        [Required(ErrorMessage = "Please Enter Password")]
        [Display(Name = "Please Enter Password")]
        public string passcode { get; set; }
        public int isActive { get; set; }

    }
}

Create Dbcontext Class

DbContext is class in Entity Framework API. It is a bridge between your domain class and the database. DbContext is the class that is responsible for interacting with the database. As per Microsoft  “A DbContext instance represents a combination of the Unit Of Work and Repository pattern such that it can be used to query from a database”

using Microsoft.EntityFrameworkCore;

namespace Auth_Login.Models
{
    public class LoginDbcontext : DbContext 
    {
        public LoginDbcontext(DbContextOptions<LoginDbcontext> options)
            :base(options)
        {

        }

        public DbSet<UserLogin> UserLogin { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<UserLogin>(entity=> {
                entity.HasKey(k=>k.id);
                });
        }
    }
}

Create a Repository and interface

Now create a repository folder, in this folder create two class, Create Interface  ILogin.cs file and AuthenticateLogin.cs

ILogin.cs

using System.Collections.Generic;
using System.Threading.Tasks;
using Auth_Login.Models;

namespace Auth_Login.Repository
{
    public interface ILogin
    {
        Task<IEnumerable<UserLogin>> getuser();
        Task<UserLogin> AuthenticateUser(string username,string passcode);
    }
}

AuthenticateLogin.cs

using Auth_Login.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Auth_Login.Repository
{
    public class AuthenticateLogin : ILogin
    {
        private readonly LoginDbcontext _context;

        public AuthenticateLogin(LoginDbcontext context)
        {
            _context = context; 
        }
        public async Task<UserLogin> AuthenticateUser(string username, string passcode)
        {
           var succeeded = await _context.UserLogin.FirstOrDefaultAsync(authUser => authUser.UserName == username && authUser.passcode == passcode);
           return succeeded;
        }

        public async Task<IEnumerable<UserLogin>> getuser()
        {
             return await _context.UserLogin.ToListAsync(); 
        }
    }
}

Configure Startup Class

Update startup class with database connection and as well as inject services.
Startup.cs

using Microsoft.EntityFrameworkCore;
using Auth_Login.Models;
using Auth_Login.Repository;
public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<LoginDbcontext>(conn => conn.UseSqlServer(Configuration.GetConnectionString("connectionstr")));
            services.AddScoped<ILogin, AuthenticateLogin>();

            services.AddControllersWithViews();
        }

Migration

Then create a Database through Migration. Go to Tools>NuGet Package Manager>Package Manager Console then execute the following commands.

Add-Migration “Initial Create”

Update-Database

Create Controller

Now create IActionResult Index Method with the parameter

using Auth_Login.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Auth_Login.Repository;

namespace Auth_Login.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogin _loginUser;

        public HomeController(ILogin loguser)
        {
            _loginUser = loguser;   
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(string username,string passcode)
        {
            var issuccess = _loginUser.AuthenticateUser(username, passcode);


            if (issuccess.Result != null)
            {
                ViewBag.username = string.Format("Successfully logged-in", username);

                TempData["username"] = "Ahmed";
                return RedirectToAction("Index", "Layout"); 
            }
            else {
                ViewBag.username = string.Format("Login Failed ", username);
                return View();
            } 
        } 
       
    }
}

Customize View Index

Go to Views>Home>Index cshtml file update.

<html>
<head>

 <link rel="stylesheet" href="~/css/Style.css" />
</head>

<body>
<div class="login">
  <h1>Login to Web App</h1>

  <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index" >
    <p><input type="text" name="username" value="" placeholder="Username or Email" required></p>     
    <p><input type="password" name="passcode" value="" placeholder="Password" required></p>     
    <p class="remember_me">
      <label>
        <input type="checkbox" name="remember_me" id="remember_me">
        Remember me on this computer
      </label>
    </p>
    <p class="submit"><input type="submit" name="commit" value="Login"></p>
    <hr/>
    @ViewBag.username
  </form>
</div> 
</body>
</html>

Create style.css  file in  wwwroot>css>style.css

body {
    font: 13px/20px "Lucida Grande", Tahoma, Verdana, sans-serif;
    color: #404040;
    background: #0ca3d2;
}

.login {
    position: relative;
    margin: 30px auto;
    padding: 20px 20px 20px;
    margin-top : 200px;
    width: 310px;
    background: white;
    border-radius: 3px;
    -webkit-box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0 0 200px rgba(255, 255, 255, 0.5), 0 1px 2px rgba(0, 0, 0, 0.3);
}
 

    .login:before {
        content: '';
        position: absolute;
        top: -8px;
        right: -8px;
        bottom: -8px;
        left: -8px;
        z-index: -1;
        background: rgba(0, 0, 0, 0.08);
        border-radius: 4px;
    }

    .login h1 {
        margin: -20px -20px 21px;
        line-height: 40px;
        font-size: 15px;
        font-weight: bold;
        color: #555;
        text-align: center;
        text-shadow: 0 1px white;
        background: #f3f3f3;
        border-bottom: 1px solid #cfcfcf;
        border-radius: 3px 3px 0 0;
        background-image: -webkit-linear-gradient(top, whiteffd, #eef2f5);
        background-image: -moz-linear-gradient(top, whiteffd, #eef2f5);
        background-image: -o-linear-gradient(top, whiteffd, #eef2f5);
        background-image: linear-gradient(to bottom, whiteffd, #eef2f5);
        -webkit-box-shadow: 0 1px whitesmoke;
        box-shadow: 0 1px whitesmoke;
    }

    .login p {
        margin: 20px 0 0;
    }

        .login p:first-child {
            margin-top: 0;
        }

    .login input[type=text], .login input[type=password] {
        width: 278px;
    }

    .login p.remember_me {
        float: left;
        line-height: 31px;
    }

        .login p.remember_me label {
            font-size: 12px;
            color: #777;
            cursor: pointer;
        }

        .login p.remember_me input {
            position: relative;
            bottom: 1px;
            margin-right: 4px;
            vertical-align: middle;
        }

    .login p.submit {
        text-align: right;
    }

.login-help {
    margin: 20px 0;
    font-size: 11px;
    color: white;
    text-align: center;
    text-shadow: 0 1px #2a85a1;
}

    .login-help a {
        color: #cce7fa;
        text-decoration: none;
    }

        .login-help a:hover {
            text-decoration: underline;
        }

:-moz-placeholder {
    color: #c9c9c9 !important;
    font-size: 13px;
}

::-webkit-input-placeholder {
    color: #ccc;
    font-size: 13px;
}

input {
    font-family: 'Lucida Grande', Tahoma, Verdana, sans-serif;
    font-size: 14px;
}

    input[type=text], input[type=password] {
        margin: 5px;
        padding: 0 10px;
        width: 200px;
        height: 34px;
        color: #404040;
        background: white;
        border: 1px solid;
        border-color: #c4c4c4 #d1d1d1 #d4d4d4;
        border-radius: 2px;
        outline: 5px solid #eff4f7;
        -moz-outline-radius: 3px;
        -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
        box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.12);
    }

        input[type=text]:focus, input[type=password]:focus {
            border-color: #7dc9e2;
            outline-color: #dceefc;
            outline-offset: 0;
        }

    input[type=submit] {
        padding: 0 18px;
        height: 29px;
        font-size: 12px;
        font-weight: bold;
        color: #527881;
        text-shadow: 0 1px #e3f1f1;
        background: #cde5ef;
        border: 1px solid;
        border-color: #b4ccce #b3c0c8 #9eb9c2;
        border-radius: 16px;
        outline: 0;
        -webkit-box-sizing: content-box;
        -moz-box-sizing: content-box;
        box-sizing: content-box;
        background-image: -webkit-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: -moz-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: -o-linear-gradient(top, #edf5f8, #cde5ef);
        background-image: linear-gradient(to bottom, #edf5f8, #cde5ef);
        -webkit-box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
        box-shadow: inset 0 1px white, 0 1px 2px rgba(0, 0, 0, 0.15);
    }

        input[type=submit]:active {
            background: #cde5ef;
            border-color: #9eb9c2 #b3c0c8 #b4ccce;
            -webkit-box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
            box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.2);
        }

.lt-ie9 input[type=text], .lt-ie9 input[type=password] {
    line-height: 34px;
}

 Then build the project and Execute it.

The post How to create Login Page using Asp.net Core MVC C# With Database appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-login-page-using-asp-net-core-mvc-c-with-database/feed/ 5 481