ZDIRY-TUFWT-EBONM-EYJ00-IDBLANTER.COM
ZDIRY-TUFWT-EBONM-EYJ00

BLANTERWISDOM105

Membuat User, Password, confirmation email di ASP NET MVC

5/15/2020

Pada Artikel ini, akan memberikan cara membuat User Login dan Password di ASP NET. Dimana user harus melakukan verifikasi terlebih dahulu sebelum login dan ada fitur recovery password apabila lupa password.

Agar mempermudah pembahasan maka Agung Panduan memecahkannya menjadi beberapa topik inti, yaitu:

  1. Registration form
  2. Password Encryption
  3. Email notification
  4. Generate User verification link
  5. Login form
  6. Forget Password
  7. Generate OTP
  8. Change Password

Registration form

Langkah 1

Buat Table Registration Table di SQL Server dengan nama database UserLogin (bebas).


CREATE TABLE [dbo].[UserM](  
    [UserId] [int] IDENTITY(1,1) NOT NULL,  
    [FirstName] [varchar](50) NOT NULL,  
    [LastName] [varchar](50) NOT NULL,  
    [Email] [nvarchar](50) NOT NULL,  
    [Password] [nvarchar](250) NOT NULL,  
    [EmailVerification] [bit] NULL,  
    [ActivetionCode] [uniqueidentifier] NULL,  
    [OTP] [nvarchar](4) NULL,  
 CONSTRAINT [PK_UserM] PRIMARY KEY CLUSTERED   
(  
    [UserId] ASC  
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]  
) ON [PRIMARY]  
  
GO

Langkah 2

Update ADO.NET Entity Data Model yang terbaru di sini

Buka Visual Studio 2012 dan buat project baru “ASP NET MVC Web Application” dengan nama “UserLogin”.

Cara Buat Project Baru ASP NET MVC

Gunakan Template Empty.

Cara Buat Project Baru ASP NET MVC 2

Langkah 3

Buat folder “DBContext” dalam project, klik kanan mouse pada folder tersebut, lalu pilih Add > New Item > Data > ADO.NET Entity Data Model.

Gunakan Model Content Empty EF Designer Model.

Langkah 4

Buat koneksi ke Sql Server dengan cara klik Server Explorer disebelah kiri monitor. Klik pada Data Connections lalu pilih Add Connection. Refresh Server Name, Pilih Use SQL Server Authentication dengan Username: sa dan password: ******. Select or Enter a database name: “TEST”.

Langkah 5

Klik kanan mouse pada lembar kerja The Entity Data Mode Designer dan pilih Update Model From Database.

Add Connection SQL Server ASP NET MVC

Hasilnya seperti di bawah ini,

Catatan:

Anda dapat Remove from diagram dan apabila ingin dikembalikan ke diagram cukup dengan drag and drop dari DbModel > Entity Type > UserM di Model Browser.

Apabila Entity Framework tidak ditemukan pada project, kamu dapat download dan install menggunakan NuGet Package Manager.

Langkah 6

Sekarang buatlah class UserRegistration.cs ke dalam folder Models.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace UserLogin.Models
{
    public class UserRegistration
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string ConfirmPassword { get; set; } 
    }
}

Kita membutuhkan proses validasi dari sisi Server untuk itu perlu kita gunakan System.ComponentModel.DataAnnotations sehingga UserRegistration.cs menjadi,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace UserLogin.Models
{
    public class UserRegistration
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "First Name is requierd")]
        public string FirstName { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Last Name is requierd")]
        public string LastName { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Email ID is requierd")]
        public string Email { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Password is requierd")]
        [DataType(DataType.Password)]
        [MinLength(6, ErrorMessage = "Need min 6 character")]
        public string Password { get; set; }
        [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password is requierd")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Confirm Password should match with Password")]
        public string ConfirmPassword { get; set; } 
    }
}

Ini harusnya hanya untuk konfirmasi kata sandi yang tidak akan kami simpan dalam basis data.

Encrypt Password

Demi keamanan, password selalu disimpan dalam format terenkripsi. Jadi, kami akan menambahkan class yang akan mengubah password menjadi format enkripsi.

Langkah 1

Tambahkan class encryptPassword.cs ini di folder Model.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;

namespace UserLogin.Models
{
    public static class encryptPassword
    {
        public static string textToEncrypt(string paasWord)
        {
            return Convert.ToBase64String(System.Security.Cryptography.SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(paasWord)));
        }
    }  
}

Langkah 2

Tambahkan RegisterController.cs pada folder Controllers.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace UserLogin.Controllers
{
    public class RegisterController : Controller
    {
        //
        // GET: /Register/
        public ActionResult Index()
        {
            return View();
        }
    }
}

Langkah 3

Buat folder Register (harus sama dengan nama Controller) dan tambahkan view Index.cshtml.


@model UserLogin.Models.UserRegistration  
  
@{  
    ViewBag.Title = "Index";  
}  
  
<h2>User Registration</h2>  
  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
       <div class="form-group">  
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Langkah 4

Install-Package Script Jquery dengan menggunakan Nuget Package Manager Console.

PM> Install-Package jQuery -Version 1.10.2

PM> Install-Package jQuery.Validation -Version 1.10.0

PM> Install-Package Microsoft.jQuery.Unobtrusive.Validation -Version 2.0.20505

Sekarang coba anda Run dan gunakan URL seperti ini http://localhost:....../Register

Tampilan User Registration ASP NET MVC

Langkah 5

Disini, anda akan melihat Registration Form menggunakan validasi. Sekarang, kita akan menunjukkan bagaimana cara menggunakan database.

Pertama, atur koneksi entitas database

Kemudian, tambahkan metode POST seperti di bawah ini dan tambahkan object yang akan mengirimkan data. Tambahkan metode return static yang mengubah kata sandi menjadi format terenkripsi.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserLogin.DBContext;

namespace UserLogin.Controllers
{
    public class RegisterController : Controller
    {
        //
        // GET: /Register/
        public ActionResult Index()
        {
            return View();
        }

        #region entity connection
        SQLDbModelEntities objCon = new SQLDbModelEntities();
        #endregion

        #region Registration post method for data save
        [HttpPost]
        public ActionResult Index(UserM objUsr)
        {
            // email not verified on registration time  
            objUsr.EmailVerification = false;
            //it generate unique code     
            objUsr.ActivetionCode = Guid.NewGuid();
            //password convert  
            objUsr.Password = UserLogin.Models.encryptPassword.textToEncrypt(objUsr.Password);
            objCon.UserMs.Add(objUsr);
            objCon.SaveChanges();
            return View();
        }
        #endregion  
    }
}

Langkah 6

Kita sekarang akan mencoba debugging proses saat melakukan ‘Create’ data baru ke dalam database.

Langkah 7

Selanjutnya cek database pada SQL server apakah data sudah masuk atau belum.

Check Jika Email Exists or Not

Ketika kami telah membuat formulir pendaftaran dengan ID email, id email harus unik. Jadi, setiap kali kami mendaftar, perlu untuk memeriksa apakah ada id email di database kami atau tidak.

Langkah 1

Untuk itu, kita akan menggunakan kode di bawah ini.


#region Check Email Exists or not in DB
        public bool IsEmailExists(string eMail)
        {
            var IsCheck = objCon.UserMs.Where(email => email.Email == eMail).FirstOrDefault();
            return IsCheck != null;
        }
        #endregion

Langkah 2

Tambahkan kode di dalam Metode POST ActionResult Index(UserM objUsr) sebelum Save Data.


var IsExists = IsEmailExists(objUsr.Email);
if (IsExists) {
   ModelState.AddModelError("EmailExists", "Email Already Exists");
   return View();
}

Sehingga RegisterController.cs menjadi,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using UserLogin.DBContext;

namespace UserLogin.Controllers
{
    public class RegisterController : Controller
    {
        //
        // GET: /Register/
        public ActionResult Index()
        {
            return View();
        }

        #region entity connection
        SQLDbModelEntities objCon = new SQLDbModelEntities();
        #endregion

        #region Registration post method for data save
        [HttpPost]
        public ActionResult Index(UserM objUsr)
        {
            // email not verified on registration time  
            objUsr.EmailVerification = false;
            //it generate unique code     

            //Email Exist or Not
            var IsExists = IsEmailExists(objUsr.Email);
            if (IsExists) {
                ModelState.AddModelError("EmailExists", "Email Already Exists");
                return View();
            }
            objUsr.ActivetionCode = Guid.NewGuid();
            //password convert  
            objUsr.Password = UserLogin.Models.encryptPassword.textToEncrypt(objUsr.Password);
            objCon.UserMs.Add(objUsr);
            objCon.SaveChanges();
            return View();
        }
        #endregion  

        #region Check Email Exists or not in DB
        public bool IsEmailExists(string eMail)
        {
            var IsCheck = objCon.UserMs.Where(email => email.Email == eMail).FirstOrDefault();
            return IsCheck != null;
        }
        #endregion
    }
}

Langkah 3

Tambahkan code di bawah ini di dalam Index.cshtml di bawah @Html.ValidationMessageFor untuk email

@Html.ValidationMessage("EmailExists"new { @class = "text-danger" }) 

Sehingga Index.cshtml menjadi,


@model UserLogin.Models.UserRegistration  
  
@{  
    ViewBag.Title = "Index";  
}  
  
<h2>User Registration</h2>  
  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })  
                @Html.ValidationMessage("EmailExists", new { @class = "text-danger" }) 
            </div>  
        </div>  
  
       <div class="form-group">  
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Apabila kita running dan masukan email yang pernah digunakan maka tampilan View akan menampilkan sebuah pesan,

Email Notification

Sekarang, kita akan menunjukkan cara mengirim email konfirmasi setelah melakukan register. Saat mengirim akan ada tautan verifikasi dengan email.

Langkah 1

Tambahkan Refererences di controllers,

using System.Net;

using System.Net.Mail;

dan tambahkan Metode SendEmailToUser() pada RegisterController.cs


public void SendEmailToUser(string emailId, string activationCode)
{
	var GenarateUserVerificationLink = "/Register/UserVerification/" + activationCode;
	var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);
	
	var fromMail = new MailAddress("youremail@gmail.com", "Agung Panduan"); // set your email  
	var fromEmailpassword = "*******"; // Set your password   
	var toEmail = new MailAddress(emailId);
	
	var smtp = new SmtpClient();
	smtp.Host = "smtp.gmail.com";
	smtp.Port = 587;
	smtp.EnableSsl = true;
	smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
	smtp.UseDefaultCredentials = false;
	smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);
	
	var Message = new MailMessage(fromMail, toEmail);
	Message.Subject = "Registration Completed-Demo";
	Message.Body = "<br/> Your registration completed succesfully." +
					"<br/> please click on the below link for account verification" +
					"<br/><br/><a href=" + link + ">" + link + "</a>";
	Message.IsBodyHtml = true;
	smtp.Send(Message);
}

Tambahkan code di bawah ini di dalam RegisterController.cs di bawah objCon.SaveChanges().

//Send Email Verification Link

SendEmailToUser(objUsr.Email, objUsr.ActivetionCode.ToString());

var Message = "Registration Completed. Please Check your Email: " + objUsr.Email;

ViewBag.Message = Message;

Langkah 2

Kemudian, tambahkan Registration View untuk menampilkan pesan bahwa user diharuskan mengecek pesan masuk di email.


@{  
    ViewBag.Title = "Registration";  
}  
  
<h2>Registration Complete</h2>  
  
<div class="alert-success">  
   <strong>Message: </strong> @ViewBag.Message  
</div>

Langkah 3

Aktifkan penggunaan akun gmail untuk Visual Studio dengan cara masuk ke Akun Gmail yang kamu gunakan lalu Kelola Akun Google Anda > Keamanan > Akses aplikasi yang kurang aman. Klik tombol Aktifkan akses (tidak direkomendasikan).

Setelah pendaftaran berhasil, email dengan tautan verifikasi dikirim.

Setelah pendaftaran berhasil, email dengan tautan verifikasi dikirim.

Verification from Email Account

Ketika anda melakukan registrasi dengan email selalu ada perintah untuk melakukan verifikasi email kepemilikan email. Maka diperlukan metode verifikasi yaitu,


#region Verification from Email Account.
public ActionResult UserVerification(string id)
{
    bool Status = false;

    objCon.Configuration.ValidateOnSaveEnabled = false; // Ignor to password confirmation   
    var IsVerify = objCon.UserMs.Where(u => u.ActivetionCode == new Guid(id)).FirstOrDefault();

    if (IsVerify != null)
    {
        IsVerify.EmailVerification = true;
        objCon.SaveChanges();
        ViewBag.Message = "Email Verification completed";
        Status = true;
    }
    else
    {
        ViewBag.Message = "Invalid Request...Email not verify";
        ViewBag.Status = false;
    }

    return View("UserVerification");
}
#endregion

Tidak hanya penambahan method ActionResult namun juga diperlukan pesan yang menunjukkan bahwa verifikasi email telah di lakukan.


@{  
    ViewBag.Title = "UserVerification";  
}  
  
<h2>User Verification Process</h2>  
  
<div class="danger alert-danger">  
    <strong>Message..!!</strong>  @ViewBag.Message,  please click here to Login @Html.ActionLink("Login", "Login", "Register")  
</div>

Ketika anda klik tautan pada email kita dapat melihat hasil debugging seperti di bawah ini,

Setelah melakukan verifikasi akan terjadi proses update table pada kolom EmailVerification yang tadinya angka 0 menjadi 1.


User Login Form

Setelah melakukan registrasi biasanya user akan di anjurkan untuk klik tautan login ataupun langsung ke halaman login.

Langkah 1

Tambahkan Class Userlogin.cs ke folder Models.


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web; 

namespace UserLogin.Models
{
    public class Userlogin
    {
        [Display(Name = "User Email ID")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "User Email Id Required")]

        public string EmailId { get; set; }
        [Display(Name = "Password")]
        [DataType(DataType.Password)]
        [Required(AllowEmptyStrings = false, ErrorMessage = "Password Required")]
        public string Password { get; set; }

        [Display(Name = "Remember Me")]
        public bool Rememberme { get; set; }  
    }
}

Langkah 2

Tambahkan Login.cshtml pada folder Register.


@model UserLogin.Models.Userlogin 
  
@{  
    ViewBag.Title = "Login";  
}  
  
<h2>Login</h2>  
  
  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Rememberme, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                <div class="checkbox">  
                    @Html.EditorFor(model => model.Rememberme)  
                    @Html.ValidationMessageFor(model => model.Rememberme, "", new { @class = "text-danger" })  
                </div>  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Login" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
  
<div>  
    @Html.ActionLink("Back to List", "Index")  
</div>  
  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Langkah 3

Sekarang, kita akan menambahkan metode POST Login. Dalam metode ini, akan ada proses pemeriksaan apakah User ada pada database atau tidak dan generate untuk cookie value untuk checkbox-Remember Me.


public ActionResult Login() {
            return View();
}
[HttpPost]
public ActionResult Login(UserLogin.Models.UserLogin LgnUsr)
{
    var _passWord = UserLogin.Models.encryptPassword.textToEncrypt(LgnUsr.Password);
    bool Isvalid = objCon.UserMs.Any(x => x.Email == LgnUsr.EmailId && x.EmailVerification == true &&
    x.Password == _passWord);
    if (Isvalid)
    {
        int timeout = LgnUsr.Rememberme ? 60 : 5; // Timeout in minutes, 60 = 1 hour.  
        var ticket = new FormsAuthenticationTicket(LgnUsr.EmailId, false, timeout);
        string encrypted = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
        cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
        cookie.HttpOnly = true;
        Response.Cookies.Add(cookie);
        return RedirectToAction("Index", "UserDash");
    }
    else
    {
        ModelState.AddModelError("", "Invalid Information... Please try again!");
    }
    return View();
}

Tambahkan juga referencesnya yaitu,

using UserLogin.Models;

using System.Web.Security;

Langkah 4

User yang memiliki akses akan diarahkan ke beranda setelah berhasil masuk. Namun sebelum masuk ke dalam Beranda User akan cek Otorisasi terlebih dahulu untuk tujuan keamanan. Untuk itu ditambahkan UserDashController.cs.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace UserLogin.Controllers
{
    public class UserDashController : Controller
    {
        // GET: /UserDash/
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }

        [Authorize]
        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Login", "Register");
        } 
    }
}

Anda dapat melihat di sini bahwa User telah berhasil login dan cookie yang dihasilkan ditemukan di browser.

Langkah 5

Sekarang, kita memerlukan kode logout untuk logout aplikasi. Untuk logout, tambahkan metode logout di controller, seperti yang ditunjukkan di bawah ini.


[Authorize]
public ActionResult LogOut()
{
    FormsAuthentication.SignOut();
    return RedirectToAction("Login", "Register");
}

Untuk proses login, kami menggunakan mode otentikasi formulir, jadi perlu beberapa perubahan seperti di bawah ini di web.config. Di sini Anda dapat melihat mengatur mode autentikasi dan mengatur URL login default.

<authentication mode="Forms"> 

      <forms cookieless="UseCookies" loginUrl="Register/Login"></forms> 

</authentication>

Simpan di dalam <system.web>

Forget Password

Tidak semua orang ingat dengan username dan password yang telah dibuat sebelumnya pada situs tertentu. Rata-rata web application selalu menyediakan fitur Forget Password, fitur ini sangat membantu para user apabila lupa password.

Langkah 1

Tambahkan Model baru dengan nama ForgetPassword, simpan pada folder Models.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace UserLogin.Models
{
    public class ForgetPassword
    {
        [Display(Name = "User Email ID")]
        [Required(AllowEmptyStrings = false, ErrorMessage = "User Email Id Required")]
        public string EmailId { get; set; }
    }
}

Langkah 2

Tambah metode View ActionResult ForgetPassword ke dalam RegisterController.cs dan metode POST untuk mengatur "Forget Password". Dengan menggunakan metode ini, kami akan menghasilkan OTP dan kemudian mengirim email ke pengguna dengan URL perubahan Password. Di dalam metode ini, kami juga akan memeriksa apakah id email pengguna sudah benar atau tidak.


public ActionResult ForgetPassword()
{
    return View();
}

[HttpPost]
public ActionResult ForgetPassword(ForgetPassword pass)
{
    var IsExists = IsEmailExists(pass.EmailId);
    if (!IsExists)
    {
        ModelState.AddModelError("EmailNotExists", "This email is not exists");
        return View();
    }
    var objUsr = objCon.UserMs.Where(x => x.Email == pass.EmailId).FirstOrDefault();

    // Genrate OTP   
    string OTP = GeneratePassword();

    objUsr.ActivetionCode = Guid.NewGuid();
    objUsr.OTP = OTP;
    objCon.Entry(objUsr).State = System.Data.Entity.EntityState.Modified;
    objCon.SaveChanges();

    ForgetPasswordEmailToUser(objUsr.Email, objUsr.ActivetionCode.ToString(), objUsr.OTP);
    return View();
}

public string GeneratePassword()
{
    string OTPLength = "4";
    string OTP = string.Empty;

    string Chars = string.Empty;
    Chars = "1,2,3,4,5,6,7,8,9,0";

    char[] seplitChar = { ',' };
    string[] arr = Chars.Split(seplitChar);
    string NewOTP = "";
    string temp = "";
    Random rand = new Random();
    for (int i = 0; i < Convert.ToInt32(OTPLength); i++)
    {
        temp = arr[rand.Next(0, arr.Length)];
        NewOTP += temp;
        OTP = NewOTP;
    }
    return OTP;
}

public void ForgetPasswordEmailToUser(string emailId, string activationCode, string OTP)
{
    var GenarateUserVerificationLink = "/Register/ChangePassword/" + activationCode;
    var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);

    var fromMail = new MailAddress("youremail@gmail.com", "Agung Kasep"); // set your email  
    var fromEmailpassword = "*******"; // Set your password   
    var toEmail = new MailAddress(emailId);

    var smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);

    var Message = new MailMessage(fromMail, toEmail);
    Message.Subject = "Password Reset-Demo";
    Message.Body = "<br/> Your registration completed succesfully." +
                   "<br/> please click on the below link for account verification" +
                   "<br/><br/><a href=" + link + ">" + link + "</a>" +
       "<br/>OTP for password change: " + OTP;
    Message.IsBodyHtml = true;
    smtp.Send(Message);
}

Langkah 3

Tambahkan ForgetPassword.cshtml pada folder Register.


@model UserLogin.Models.ForgetPassword  
  
@{  
    ViewBag.Title = "ForgetPassword";  
}  
  
<h2>ForgetPassword</h2>  
  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()      
    <div class="form-horizontal">  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.EmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.EmailId, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.EmailId, "", new { @class = "text-danger" })  
@Html.ValidationMessage("EmailNotExists", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
  
<div>  
    @Html.ActionLink("Back to List", "Index")  
</div>  
  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Langkah 4

Lakukan sedikit perubahan pada Login.cshtml yaitu menambahkan kode di bawah ini,


<div>
   @Html.ActionLink("Registration", "Index") ||  
   @Html.ActionLink("Reset Passward", "ForgetPassword")
</div>

Langkah 5

Sekarang jalankan aplikasi dan jangan lupa tekan tombol Forget Password dan isi email yang pernah digunakan untuk mendaftar.

Email yang diperoleh setelah Reset Password berisi tautan yang harus dikunjungi untuk login beserta OTP yang dikirim oleh web application.

Apabila tautan yang dikirim oleh web application di klik oleh user maka akan menuju view ChangePassword. Untuk melakukan perubahan password dibutuh OTP yang dikirim ke email.

Change Password

Langkah 6

Tambahkan Model baru dengan nama ChangePassword, simpan pada folder Models,


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; 

namespace UserLogin.Models
{
    public class ChangePassword
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "OTP is requierd")]
        public string OTP { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Password is requierd")]
        [DataType(DataType.Password)]
        [MinLength(6, ErrorMessage = "Need min 6 char")]
        public string Password { get; set; }

        [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password is requierd")]
        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "Confirm Password should match with Password")]
        public string ConfirmPassword { get; set; }  
    }
}

Langkah 7

Tambahkan ChangePassword.cshtml pada folder Register.


@model UserLogin.Models.ChangePassword  
  
@{  
    ViewBag.Title = "ChangePassword";  
}  
  
<h2>ChangePassword</h2>  
  
  
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
        <h4>ChangePassword</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.OTP, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.OTP, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.OTP, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            @Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { @class = "text-danger" })  
            </div>  
        </div>  
  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Change Password" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
  
<div>  
    @Html.ActionLink("Login", "Login")  
</div>  
  
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script src="~/Scripts/jquery.validate.min.js"></script>  
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Langkah 8

Tambah metode View ActionResult ChangePassword ke dalam RegisterController.cs dan metode POST untuk mengatur "Change Password". Dengan metode ini kita akan mengirim halaman login dan password baru yang telah dibuat.


public ActionResult ChangePassword()
{
    return View();
}

#region Update post method for data save
[HttpPost]
public ActionResult ChangePassword(ChangePassword objUsr)
{
    //var UserData = objCon.UserMs.Where(c => c.OTP == objUsr.OTP && c.Password == objUsr.Password).FirstOrDefault();

    var UserData = objCon.UserMs.Where(c => c.OTP == objUsr.OTP).FirstOrDefault();
    if (UserData != null)
    {
        UserData.Password = UserLogin.Models.encryptPassword.textToEncrypt(objUsr.ConfirmPassword);
        objCon.Entry(UserData).State = System.Data.Entity.EntityState.Modified;
        objCon.SaveChanges();
    }
    //Send Email
    SendChangePasswordToUser(UserData.Email, objUsr.ConfirmPassword);
    var Message = "Change Password Completed. Please Check your Email: " + UserData.Email;
    ViewBag.Message = Message;

    return View();
}
#endregion 

public void SendChangePasswordToUser(string emailId, string password)
{
    var GenarateUserVerificationLink = "/Register/Login/";
    var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, GenarateUserVerificationLink);

    var fromMail = new MailAddress("onepunchbotak@gmail.com", "Agung Kasep"); // set your email  
    var fromEmailpassword = "agungkazama1"; // Set your password   
    var toEmail = new MailAddress(emailId);

    var smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtp.UseDefaultCredentials = false;
    smtp.Credentials = new NetworkCredential(fromMail.Address, fromEmailpassword);

    var Message = new MailMessage(fromMail, toEmail);
    Message.Subject = "Change Password Completed-Demo";
    Message.Body = "<br/> Change Password completed succesfully." +
                   "<br/> please click on the below link for login" +
                   "<br/><br/><a href=" + link + ">" + link + "</a>" +
                   "<br/> Your New Password: " + password;
    Message.IsBodyHtml = true;
    smtp.Send(Message);
}

Langkah 9

Sekarang, anda klik tautan yang ada pada email yang dikirim Web Application lalu masukan OTP dan buat password baru.

Demikianlah cara membuat form login yang dilengkapi dengan Verifikasi Kepemilikan User dengan Email, Forget Password, Change Password. Jika kalian ingin melihat contoh lengkapnya bisa download link di bawah ini,

Share This :

0 Comments