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中添加啓動認證或者不啓用認證隨意配置

相關文章
相關標籤/搜索