asp.net core 登录身份认证(Cookie)
程序员文章站
2022-06-09 15:47:40
asp.net core 2最简单的登录功能 源代码在此 创建asp.net core Web Mvc项目 配置下选项 项目目录结构 在Models文件夹下新建两个实体类 在项目文件夹下新建Data文件夹,新建DbContext类 在Startup.cs文件中的ConfigureServices下添 ......
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中添加启动认证或者不启用认证随意配置
下一篇: java 可变长参数
推荐阅读
-
浅谈如何在ASP.NET Core中实现一个基础的身份认证
-
详解ASP.NET Core和ASP.NET Framework共享身份验证
-
详解ASP.NET Core Token认证
-
在ASP.NET Core中实现一个Token base的身份认证实例
-
详解在ASP.NET Core中使用Angular2以及与Angular2的Token base身份认证
-
【翻译】使用WebApi和Asp.Net Core Identity 认证 Blazor WebAssembly(Blazor客户端应用)
-
Nodejs进阶:express+session实现简易登录身份认证
-
ASP.NET Core集成微信登录
-
ASP.NET Core身份认证服务框架IdentityServer4 介绍
-
【.NET Core微服务实战-统一身份认证】开篇及目录索引