asp.net core 登录身份认证(Cookie)

asp.net core 2最简单的登录功能

 源代码在此

创建asp.net core Web Mvc项目

配置下选项

项目目录结构

 

在Models文件夹下新建两个实体类

    public class Test
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "某人")]
        public string Someone { get; set; }
        [Required]
        [Display(Name = "某事")]
        public string Something { get; set; }

    }
    public class User
    {
        public int Id { get; set; }
        [Required]
        [Display(Name = "用户名")]
        public string UserName { get; set; }
        [Display(Name = "密码")]
        [Required]
        public string UserPwd { get; set; }
        public string Nothing { get; set; }
    }

在项目文件夹下新建Data文件夹,新建DbContext类

 

    public class MyDbContext:DbContext
    {
        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options) { }

        public DbSet<User> Users { get; set; }
        public DbSet<Test> Tests { get; set; }
    }

 

在Startup.cs文件中的ConfigureServices下添加dbcontext服务

 

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //sqlserver
            services.AddDbContext<MyDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

在appsettings.json下配置数据库连接字符串

打开程序包管理器控制台,执行生成数据库上下文和创建更新数据库命令

 

 

去数据库查看下表是否生成,并直接添加一个种子数据。

 

添加控制器和视图

 

生成之后的项目结构目录如下

 

在homecontroller中编写一个Login方法

 

public class HomeController : Controller
    {
        private readonly MyDbContext _context;

        public HomeController(MyDbContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            return View();
        }

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

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        [HttpPost]
        public async Task<IActionResult> Login(User user)
        {
            var loginuser = await _context.Users.FirstOrDefaultAsync(u => u.UserName == user.UserName);
            if (loginuser == null)
                return BadRequest("没有该用户");
            if (loginuser.UserPwd != user.UserPwd)
                return BadRequest("密码错误");

            //声明对象创建
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user.UserName)
            };
            ClaimsIdentity userIdentity = new ClaimsIdentity(claims, "login");
            ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
            await HttpContext.SignInAsync(principal);
            //写入HttpContext

            return RedirectToAction("Index", "Test");
        }
    }

在Startup中添加cookie认证服务并使用

public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //sqlserve
            services.AddDbContext<MyDbContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //添加cookie认证服务
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Home/Index/";

            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            //使用认证服务
            app.UseAuthentication();

            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

修改Views/Home/Index.cshtml为下面内容

@model CookieAuth.Models.User
@{
    ViewData["Title"] = "Home Page";
}
<div class="row">
    <div class="col-md-4">
        <section>
            <form method="post" asp-action="Login">
                <h4>Login</h4>
                <hr />

                <div class="form-group">
                    <label asp-for="UserName"></label>
                    <input asp-for="UserName" class="form-control" />
                </div>

                <div class="form-group">
                    <label asp-for="UserPwd"></label>
                    <input asp-for="UserPwd" type="password" class="form-control" />
                </div>

                <div class="form-group">
                    <button type="submit" class="btn btn-default">登录</button>
                </div>

            </form>
        </section>
    </div>
</div>

在_Layout中添加一个导航栏

 

然后在Test控制器中添加认证特性

 

就可以启动项目。

如果不没输入正确的地址是会被重定向到登录页面。

 

 

就这样先,如果是已有项目 只需要在startup中添加cookie认证服务以及在login和logout方法中创建和销毁声明。

在controller或者action中添加启动认证或者不启用认证随意配置

 

posted @ 2018-12-19 14:54  Allvirus  阅读(3286)  评论(2)    收藏  举报