ASP.NET Core EF MVC 登录验证

2021/9/6 17:08:55

本文主要是介绍ASP.NET Core EF MVC 登录验证,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

我也不是很懂,看视频学习,有如问题请指正!

根据ASP.NET Core MVC 登录验证_哔哩哔哩_bilibili视频整理

创建项目

ASP.NET Core 5.0

Entity Framework 5.0

作者使用的是MSSQL,我换成了MYSQL

首先创建项目,作者使用了ASP.NET Core Web App(MVC)模板

我创建的ASP.NET Core Web空模板

通过NuGet安装需要的插件引用

Microsoft.EntityFrameworkCore(5.0.9)

Microsoft.EntityFrameworkCore.Tools(5.0.9) 迁移相关操作需要的 实现Code First需要

Pomelo.EntityFrameworkCore.MySql(5.0.1) MySql 官方的都说不好使,我就用了这个社区的

创建User类

user.cs

using System.ComponentModel.DataAnnotations;

namespace EF1.Domain.Entities
{
    public class User
    {
        public int Id { get; set; }
        [Display(Name = "用户名")]
        [MaxLength(20,ErrorMessage = "{0}长度不能大于{1}") ]
        public string Account { get; set; }
        public string Password { get; set; }
    }
}
View Code

创建数据库操作类

MyDbContext.cs

using Microsoft.EntityFrameworkCore;
using EF1.Domain.Entities;

namespace EF1.Domain
{
    public class MyDbContext:DbContext
    {
        public DbSet<User> Users { get; set; }

        public MyDbContext(DbContextOptions options):base(options)
        {
            
        }
    }
}
View Code

设置配置文件,新增链接数据库字符串

appsettings.json

{
  "ConnectionStrings": {
    "Default": "host=localhost;port=3306;database=EFCore1;uid=root;pwd=root"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}
View Code

NetCore配置相关数据

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using EF1.Domain;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;

namespace EF1
{
    public class Startup
    {
        public IConfiguration Configuration { get; }

        //创建构造函数注入Configuration配置项
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
        public void ConfigureServices(IServiceCollection services)
        {
            //设置Mysql版本号信息,代码需要
            var serverVersion = new MySqlServerVersion(new Version(5, 5, 23));
            services.AddControllersWithViews();//根据自己需求配置是增加控制器和视图,还是只增加控制器AddControllers
            services.AddDbContext<MyDbContext>(options =>
            {
                options.UseMySql(Configuration.GetConnectionString("Default"), serverVersion);
            });//注册MyDbContext服务
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
                    options.LoginPath = "/home/login";
                });//权限验证配置
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseRouting();
            //登陆验证
            app.UseAuthentication();
            //授权验证
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}
View Code

授权验证相关

对于需要授权的相关类或者方法增加[Authorize]验证属性访问这些类或者方法就会触发登陆验证

当类设置有[Authorize]验证属性的,如果想给个别方法取消验证可以给对应方法上增加[AllowAnonymous]属性则不验证该方法

登陆退出相关代码

using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using EF1.Domain;
using EF1.Domain.Entities;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.EntityFrameworkCore;

namespace EF1.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        private readonly MyDbContext _context;

        public HomeController(MyDbContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            return Json("Home/Index"+HttpContext.User.Identity.Name);
        }
        /// <summary>
        /// 登陆访问页
        /// </summary>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult Login(string returnUrl)
        {
            ViewBag.returnUrl = returnUrl;
            return View();
        }
        /// <summary>
        /// 登陆请求Post页面
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> Login(UserLoginRequest user)
        {
            if (ModelState.IsValid)//模型数据验证
            {
                if (await _context.Users.AnyAsync(a => a.Account == user.Account && a.Password == user.Password))//登陆验证
                {
                    var claims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, user.Account)
                    };//需要记录存储的数据,格式我也不会,死记硬背吧..
                    var claimnsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    await HttpContext.SignInAsync(new ClaimsPrincipal(claimnsIdentity),new AuthenticationProperties{IsPersistent = true});
                }
                else
                {
                    return RedirectToAction(nameof(Login));
                }
            }
            else
            {
                return UnprocessableEntity(ModelState);
            }
            return Redirect(user.ReturnUrl??"/");
        }
        /// <summary>
        /// 退出请求页面
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> LoginOut()
        {
            await HttpContext.SignOutAsync();
            return RedirectToAction(nameof(Login));
        }
    }

    public class UserLoginRequest:User
    {
        public string ReturnUrl { get; set; }
    }
}
View Code

 



这篇关于ASP.NET Core EF MVC 登录验证的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程