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

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

 源代码在此git

建立asp.net core Web Mvc项目github

配置下选项sql

项目目录结构数据库

 

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

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类cookie

 

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服务app

 

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下配置数据库链接字符串asp.net

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

 

 

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

 

添加控制器和视图

 

生成以后的项目结构目录以下

 

在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中添加启动认证或者不启用认证随意配置

相关文章
相关标签/搜索