login and registration form in asp.net core using entity Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Wed, 25 Jan 2023 10:59:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.1 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 login and registration form in asp.net core using entity Archives - Tech Insights 32 32 230003556 How to Create Registration and Login using Identity in Asp.Net Core https://reactconf.org/how-to-create-registration-and-login-using-identity-in-asp-net-core/ https://reactconf.org/how-to-create-registration-and-login-using-identity-in-asp-net-core/#respond Wed, 25 Jan 2023 10:59:17 +0000 https://labpys.com/?p=786 In this Article we will learn How to Create Registration and Login using Identity in Asp.Net Core. Prerequisites Create ASP.NET Core Web App Select framework and Click on Create Install …

The post How to Create Registration and Login using Identity in Asp.Net Core appeared first on Tech Insights.

]]>
In this Article we will learn How to Create Registration and Login using Identity in Asp.Net Core.

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here

Create ASP.NET Core Web App

  • Open visual studio and click the Create New Project Option
  • Select the Blank Template
  • Enter the name of the Project

Select framework and Click on Create

Install NuGet Packages

  • Microsoft.AspNetCore.Identity.EntityFramework
  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.InMemory

DbContext Class

DbContext Class. The DbContext is used for accessing application data through Entity Framework Core. You need to create DbContext class that derives from “IdentityDbContext” class

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace Auth_Identity_Login.Services
{

    //Identity contains all user table to inherits
    public class AppDbContext : IdentityDbContext 
    {
        public AppDbContext(DbContextOptions<AppDbContext> option)
            :base(option)
        {

        }
    }
}

Create View Model

using System.ComponentModel.DataAnnotations;

namespace Auth_Identity_Login.Models
{
    public class UserViewModel
    {
        [Key]
        public int userid { get; set; }       
        public string username { get; set; }
        public string Email { get; set; }
        public string password { get; set; }    
    }
}

Program.cs

using Auth_Identity_Login.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();


builder.Services.AddDbContext<AppDbContext>(config=>
    {
        config.UseInMemoryDatabase("Memory");

});

builder.Services.AddIdentity<IdentityUser, IdentityRole>(config=>
{
    config.Password.RequiredLength = 5;
    config.Password.RequireDigit = false;
    config.Password.RequireNonAlphanumeric = false;
    config.Password.RequireUppercase = false;

})
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

builder.Services.ConfigureApplicationCookie(config =>
{
    config.Cookie.Name = "Auth_Tutorial";
    config.LoginPath = "/Home/Login";

});

 
builder.Services.AddMvc();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

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

app.UseAuthentication();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoint =>
{
    endpoint.MapDefaultControllerRoute();

});

app.Run();

Previous Article also you can check ASP.Net Core Authentication and Authorization Basics in .Net Core 6.0

Create Controller

Create the Home Controller

using Auth_Identity_Login.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace Auth_Identity_Login.Controllers
{
    public class HomeController : Controller
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;

        public HomeController(UserManager<IdentityUser> userManager,SignInManager<IdentityUser> signInManager)
        {
            _userManager = userManager;   
            _signInManager = signInManager;
        }
        public IActionResult Index()
        {
            return View();
        }

         
        public IActionResult Register()
        {

            return View();
        }

        public IActionResult Login()
        {

            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Login(UserViewModel model)
        {
            var user = await _userManager.FindByNameAsync(model.username);

            try
            {
                           
            if (user != null)
            {
              var SignInResult = await _signInManager.PasswordSignInAsync(user, model.password,false,false);
            
            if (SignInResult.Succeeded)
            {
                    TempData["Message"] = "Logged In";
                    return RedirectToAction(nameof(Index));
                }
            }
            }
            catch (Exception)
            {

                TempData["Message"] = "User doesn't Exist";
                return RedirectToAction(nameof(Index));
            }

            TempData["Message"] = "Login Fail";
            return RedirectToAction(nameof(Index));
        }

        [HttpPost]
        public async Task<IActionResult> Register(UserViewModel model)
        {
            var userinfo = new IdentityUser
            {

                UserName = model.username,
                Email = string.Empty,
            };
           var userresult = await  _userManager.CreateAsync(userinfo,model.password);

            if (userresult.Succeeded)
            {
                var SignInResult = await _signInManager.PasswordSignInAsync(userinfo, model.password, false, false);

                if (SignInResult.Succeeded)
                {
                    TempData["Message"] = "User Registered";
                    return RedirectToAction(nameof(Index));
                }
            }
            TempData["Message"] = "User Registeration Fail";
            return RedirectToAction(nameof(Index));
        }

            
        public async Task<IActionResult> LogOut()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction(nameof(Index));
        }
        
              
       
    }
}

Create View

Index.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}
 
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" />
<br/>
<div class="container-fluid">
<div class="btn-group">
         
    <a asp-controller="Home" asp-action="Register" class="btn-primary">Register</a>
    <br/>

    <a asp-controller="Home" asp-action="Login" class="btn-primary">Login</a>

        <h1>@TempData["Message"]</h1>
    </div>
</div>  

Login.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

 
<html>
<head>

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

<body>
    <div class="login">
        <h1>Login</h1>

        <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Login">
            <p><input type="text" name="username" value="" placeholder="Username or Email" required></p>
            <p><input type="password" name="password" 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 />
             
        </form>
    </div>
</body>
</html>

Register.cshtml

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

@model Auth_Identity_Login.Models.UserViewModel

<html>
<head>

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

<body>
    <div class="login">
        <h1>User Registeration</h1>

        <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Register">
            <p><input type="text" name="username" value="" placeholder="Username or Email" required></p>
            <p><input type="password" name="password" 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="Submit"></p>
            <hr />
            
        </form>
    </div>
</body>
</html>

The post How to Create Registration and Login using Identity in Asp.Net Core appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-registration-and-login-using-identity-in-asp-net-core/feed/ 0 786
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