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 = , 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中添加启动认证或者不启用认证随意配置
asp.net core 登录身份认证(Cookie)的更多相关文章
- ASP.NET Core的身份认证框架IdentityServer4--入门
ASP.NET Core的身份认证框架IdentityServer4--入门 2018年08月11日 10:09:00 qq_42606051 阅读数 4002 https://blog.csdn ...
- ASP.NET Core的身份认证框架IdentityServer4--(4)添加第三方快捷登录
添加对外部认证的支持 接下来我们将添加对外部认证的支持.这非常简单,因为你真正需要的是一个兼容ASP.NET Core的认证处理程序. ASP.NET Core本身也支持Google,Facebook ...
- ASP.NET Core的身份认证框架IdentityServer4(9)-使用OpenID Connect添加用户认证
OpenID Connect OpenID Connect 1.0是OAuth 2.0协议之上的一个简单的身份层. 它允许客户端基于授权服务器执行的身份验证来验证最终用户的身份,以及以可互操作和类似R ...
- ASP.NET Core的身份认证框架IdentityServer4--入门【转】
原文地址 Identity Server 4是IdentityServer的最新版本,它是流行的OpenID Connect和OAuth Framework for .NET,为ASP.NET Cor ...
- ASP.NET Core的身份认证框架IdentityServer4--(3)令牌服务配置访问控制跟UI添加
使用密码保护API OAuth 2.0 资源所有者密码授权允许一个客户端发送用户名和密码到IdentityServer并获得一个表示该用户的可以用于访问api的Token. 该规范建议仅对" ...
- ASP.NET Core的身份认证框架IdentityServer4(7)- 使用客户端证书控制API访问
前言 今天(2017-9-8,写于9.8,今天才发布)一口气连续把最后几篇IdentityServer4相关理论全部翻译完了,终于可以进入写代码的过程了,比较累.目前官方的文档和Demo以及一些相关组 ...
- ASP.NET Core的身份认证框架IdentityServer4(5)- 包和构建
包和构建 IdentityServer有许多nuget包 IdentityServer4 nuget | github 包含IdentityServer核心对象模型,服务和中间件. 仅支持内存配置和用 ...
- ASP.NET Core的身份认证框架IdentityServer4(1)-特性一览
IdentityServer4是ASP.NET Core的一个包含OpenID和OAuth 2.0协议的框架.OpenID和OAuth 的区别请看 https://www.zhihu.com/ques ...
- ASP.NET Core的身份认证框架IdentityServer4--(2)API跟WEB端配置
API配置 可以使用ASP.NET Core Web API模板.同样,我们建议您控制端口并使用与之前一样的方法来配置Kestrel和启动配置文件.端口配置为http://localhost:5001 ...
随机推荐
- 成都Uber优步司机奖励政策(4月10日)
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
- (二)SpringBoot2.0基础篇- 静态资源的访问及Thymeleaf模板引擎的使用
一.描述 在应用系统开发的过程中,不可避免的需要使用静态资源(浏览器看的懂,他可以有变量,例:HTML页面,css样式文件,文本,属性文件,图片等): 并且SpringBoot内置了Thymeleaf ...
- idea css文件不识别的问题的解决方案
可以看到 progressBar不识别 发现仅仅是这一个文件名不识别 所以换一个任意别的文件名即可识别
- char和String 在jsp java代码中与jstl代码中的区别
在 jsp java代码中 '0' ,这种代表char 在jstl中 '0' 会被解释为 String 所以也可以用 .equals 方法
- Struts 2(一):初识Struts
[很久以前的笔记,后续继续完善] 在了解Struts 2框架之前,首先了解一下Model 1和Model 2架构,以及它们的优缺点. 1.1 Model 1架构模式 Model 1的核心是JSP文件, ...
- XAF-如何在详细视图界面显示按钮(含示例项目下载)
默认情况下,指定了按钮的Category后,将在对应的按钮容器显示按钮.有时候,我们需要将按钮显示在详细视图中. 本示例源码 创建一个控制器,并填加按钮.设置好了所有ID.Caption后,给Cate ...
- jquery Ajax请求中显示Loading...
jquery Ajax请求中显示Loading... $('#btnTest').click(function(){ $.ajax({ url ---- ,根据你需要设置 ...
- HTML从入门到放弃
一.HTML 简介 链接:https://www.cnblogs.com/baishuchao/articles/9179920.html 二.HTML 基础 链接:https://www.cnblo ...
- windows python MySQL-python安装过程
问题表述: pip install MySQL-python==1.2.5 出现如下报错: C:\Users\Administrator\AppData\Local\Programs\Common\M ...
- .net mvc5 不同view()的视图 代码
public class Test { public int id { set; get; } public string name { set; get; } } public ActionResu ...