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 ...
随机推荐
- 【转载】CPU阿甘
原文:CPU阿甘 前言 上帝为你关闭了一扇门,就一定会为你打开一扇窗这句话来形容我最合适不过了.我是CPU, 他们都叫我阿甘, 因为我和<阿甘正传>里的阿甘一样, 有点傻里傻气的.上帝 ...
- P3374 【模板】树状数组 1(单点增减,区间求和)
P3374 [模板]树状数组 1 题目描述 如题,已知一个数列,你需要进行下面两种操作: 1.将某一个数加上x 2.求出某区间每一个数的和 输入输出格式 输入格式: 第一行包含两个整数N.M,分别表示 ...
- Visual Studio 设置C#语言代码格式
设置代码大括号不另起一行: 工具 -> 选项 -> 文本编辑器 -> C# -> 代码样式 -> 格式设置
- TPO-17 C2 Reschedule part-time job in campus dining hall
TPO-17 C2 Reschedule part-time job in campus dining hall 第 1 段 1.Listen to a conversation between a ...
- RabbitMQ入门:在Spring Boot 应用中整合RabbitMQ
在上一篇随笔中我们认识并安装了RabbitMQ,接下来我们来看下怎么在Spring Boot 应用中整合RabbitMQ. 先给出最终目录结构: 搭建步骤如下: 新建maven工程amqp 修改pom ...
- css各种鼠标手型集合
比较齐全的鼠标手型css在国内的网站上是没搜到这么全的比如说哪个禁止的手型:鼠标往下移动即可看到效果: html代码如下: <h1>Cursors</h1> <div c ...
- [C++] Solve "Launch Failed. Binary not found." error on Eclipse
This error is that the default lanch configuration is not being created for this project. To solve i ...
- 爬虫:Scrapy12 - Stats Collection
Scrapy 提供了方便的收集数据的机制.数据以 key/value 方式存储,值大多是计数值.该机制叫做数据收集器(Stats Collector),可以通过 Crawler API 的属性 sta ...
- AppCan 之初体验
平台概述 什么是AppCan 移步这里,楼主的一句话:可以匹敌 Phonegap .Titanium .Sencha Touch .MUI .ImagApp.Nitrous .apicloud .起步 ...
- php中注释有关内容
//单行注释 /*多行注释*/ /** 文档注释 (注意 文档注释与前面的那个多行注释不同)文档注释可以和特定的程序元素相关联 例如 类 函数 常量 变量方法 问了将文档注释与元素相关联 只需要在元素 ...