Bài 7. Xây dựng trang đăng nhập quản trị web bằng netcore đơn giản nhất

Bài 7. Xây dựng trang đăng nhập quản trị web bằng netcore đơn giản nhất

Để có thể quản trị admin thì chúng ta cần phân quyền buộc người dùng phải đăng nhập mới có thể truy cập được.

Tao trang đăng nhâp đơn giản dùng boostrap nhé

1. Phần code xử lý

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace themebeautiful.Area.admin.Controllers
{
    [Area("admin")]
    public class LoginController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}

Viết thêm hàm xử lý lưu lại khi đăng nhập thành công.

      
        private async Task SignInUser(string username, bool isPersistent)
        {
            // Initialization.  
            var claims = new List<Claim>();

            try
            {
                // Setting  
                claims.Add(new Claim(ClaimTypes.Name, username));
                var claimIdenties = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var claimPrincipal = new ClaimsPrincipal(claimIdenties);
                var authenticationManager = Request.HttpContext;

                // Sign In.  
                await authenticationManager.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimPrincipal, new AuthenticationProperties() { IsPersistent = isPersistent });
            }
            catch (Exception ex)
            {
                // Info  
                throw ex;
            }
        }

Xử lý kiểm trai tài khoản nhập vào

       [HttpPost]
        public async Task<IActionResult> Index(LoginViewModel model)
        {
          if (ModelState.IsValid)
            {

              
               // có thể mã hóa password md5 sha .. 
                var loginInfo = await _context.users.FirstOrDefaultAsync(x => x.usname == model.username && x.password == model.Password);
                // Verification.  
                if (loginInfo != null)
                {



                    var userClaims = new List<Claim>()
                     {
                       new Claim(ClaimTypes.Name, loginInfo.usname),
                        new Claim("name", loginInfo.name),
                       new Claim(ClaimTypes.Role, "adm"), 
                          };

                    var grandmaIdentity = new ClaimsIdentity(userClaims, loginInfo.name);

                    var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity });
                    var claimsIdentity = new ClaimsIdentity(userClaims, CookieAuthenticationDefaults.AuthenticationScheme);

                    var authProperties = new AuthenticationProperties
                    {

                        ExpiresUtc = DateTimeOffset.UtcNow.AddDays(1),


                        IsPersistent = true,
                       
                    };
                    await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimsIdentity), authProperties);
                    if (!string.IsNullOrEmpty(model.ReturnUrl) && Url.IsLocalUrl(model.ReturnUrl))
                    {

                        return Redirect(model.ReturnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Dashboard");

                    }

                }
                else
                {
                    // Setting.  
                    ModelState.AddModelError(string.Empty, "Invalid username or password.");
                }
            }
}

 

Đăng xuất như sau

 [Route("admin/logout")]
        public async Task<IActionResult> Logout()
        {
            await Request.HttpContext.SignOutAsync();
         
            return Redirect("/");
        }

2.Phần view html như sau

@{ Layout = null;}<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Login - Administrator </title>

    <!-- Bootstrap -->
    <link href="/templates/backend/css/bootstrap.min.css" rel="stylesheet">
    <link href="/templates/backend/css/font-awesome.min.css" rel="stylesheet">
    <link href="/templates/backend/css/main.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
    <script src="/images/blog/793e079ed81088b9d24901de0c19088.jpg"></script>
    <script src="/images/blog/42e52894ed1916e4b278f3408c0bda8.jpg"></script>
    <![endif]-->
</head>
<body>
<header id="main-header">
    <div class="container">
        <div class="row">
            <div class="col-md-4 col-md-offset-4">
               <img src="/images/blog/1bb87d41d15fe27b500a4bfcde01bb0.jpg"
                     class="img-responsive col-sm-4 col-sm-offset-4" style="padding: 15px;"/>	
					 
            </div>
			<div class="col-md-4 col-md-offset-4">
               <!-- <img src="/templates/images/images/blog/1bb87d41d15fe27b500a4bfcde01bb0.jpg"
                     class="img-responsive col-sm-4 col-sm-offset-4" style="padding: 10px;"/>	 -->
					 
            </div>
        </div>
    </div>
</header>
<!-- end header -->
<section class="main" role="main">
    <div class="container">
        <div class="row">
            <div class="login-container col-md-4 col-md-offset-4" id="login-form">
    <div class="login-frame clearfix">
        <h3 class="heading col-md-10 col-md-offset-1 padd-0"><i class="fa fa-lock"></i>Đăng nhập</h3>
        <ul class="validation-summary-errors col-md-10 col-md-offset-1">
                    </ul>
        <div class="col-md-10 col-md-offset-1">
            <form class="form-horizontal login-form frm-sm" method="post" action="/admin/login">
                 <div class="form-group input-icon">
                    <label for="inputEmail3" class="sr-only control-label">Email</label>
                    <input type="text" name="username"
                           value="admin"
                           class="form-control" id="inputEmail3" placeholder="Email/Mã Đăng nhập">
                    <i class="fa fa-user icon-right"></i>
                </div>
                <div class="form-group input-icon">
                    <label for="inputPassword3" class="sr-only control-label">Password</label>
                    <input type="password" name="password"
                           value="admin"
                           class="form-control" id="inputPassword3" placeholder="Mật khẩu">
                    <i class="fa fa-lock icon-right"></i>
                </div>

                <div class="form-group">
                    <input type="submit" name="login" value="Đăng nhập" class="btn btn-primary btn-sm"/>
                </div>
				<div> <h3></h3></div>>
            </form>
        </div>
    </div>

   <div class="link-action text-center">
     <div class="col-sm-6 col-xs-12">
         <a href="#authentication/fg_password" style="display:inline-block; margin-top: 5px;" class="fg-passw">Quên
            mật khẩu</a>
      </div>
     <div class="col-sm-6 col-xs-12">
           <a href="#authentication/register" style="display:inline-block; margin-top: 5px;" class="register">Đăng
             kí</a>
      </div>

   </div>
</div>        </div>
    </div>
</section>
<!--end .main-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="/images/blog/1b4f8c8d72e9515326e896f311b4e7f.jpg"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="/images/blog/13b2a30e265e18a6fd0792cc3fd7a09.jpg"></script>
<script src="/images/blog/7a9076d6d94e62c13d641aa71f19ae8.jpg"></script>

</body>
</html>

Có thể tìm mẫu khác đẹp hơn như bên dưới


Tags

admin

Hãy chia sẽ cảm nghĩ của bạn về bài viết trên nhé !

0 Nhận xét

  • Hãy trở thành người đầu tiên viết chia sẽ cảm nghĩ của mình bên dưới nhé!

Thêm Bình luận

Tin liên quan