前言

本示例完全是基于 ASP.NET Core 3.0。本文核心是要理解 Claim, ClaimsIdentity, ClaimsPrincipal,读者如果有疑问,可以参考文章 理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文

代码

项目文件 csproj 的配置

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
</ItemGroup>
</Project>

Program.cs

注意: ASP.NET Core 3.0 的配置和 v2.2 稍微有一点不同。

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
} public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

Startup

注意:不管是 ConfigureServices 方法,还是 Configure 方法,配置的顺序至关重要,有可能明明配置了 XX,运行时却总是无效。比如笔者实验时,把 app.UseAuthentication(); 写到了 app.UseRouting() 前面,结果导致运行时,标记在 Action 方法上面的 [Authorize] 总是无效,结果发现是注册的顺序搞错了,大家一定要注意这点。

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} 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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) // Sets the default scheme to cookies
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
options.AccessDeniedPath = "/account/denied";
options.LoginPath = "/account/login";
}); services.AddControllersWithViews(); // Example of how to customize a particular instance of cookie options and
// is able to also use other services.
// will override CookieAuthenticationOptions, such as LoginPath => "/account/hello"
//services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, ConfigureMyCookie>();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseDeveloperExceptionPage(); // Temp Open
//app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); // Remember to put it behind app.UseRouting()
app.UseAuthorization(); // Remember to put it behind app.UseRouting() app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}

HomeController

在需要授权才能访问的 Action 方法上标记  [Authorize]

public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
} public IActionResult Index()
{
return View();
} [Authorize]
public IActionResult MyClaims()
{
return View();
} public IActionResult Privacy()
{
return View();
}
}

_Layout.cshtml

在这里面,可以通过 @User.Identity.IsAuthenticated 来判断用户是否已经进行了授权,如果已经授权,则显示 “Logout” 链接。

<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="MyClaims">My Claims</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy_@(User.Identity.IsAuthenticated)</a>
</li>
@if (User.Identity.IsAuthenticated)
{
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Account" asp-action="Logout">Logout</a>
</li>
}

AccountController

注意:由于之前我们在 Starup 中配置了 CookieAuthenticationOptions 类(Microsoft.AspNetCore.Authentication.Cookies. CookieAuthenticationOptions)的 options.LoginPath = "/account/login"; 这时候如果访问 /home/MyCliams 时,会自动跳转到 /account/login。

ApplicationUser

    public class ApplicationUser
{
public string Email { get; set; }
public string FullName { get; set; }
}

LoginViewModel

    public class LoginViewModel
{
public string UserName { get; set; } public string Password { get; set; }
}
    public class AccountController : Controller
{
[HttpGet]
public IActionResult Login(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
return View();
} private async Task<ApplicationUser> AuthenticateUser(string email, string password)
{
// For demonstration purposes, authenticate a user
// with a static email address. Ignore the password.
// Assume that checking the database takes 500ms await Task.Delay(); //if (email == "maria.rodriguez@contoso.com")
//{
return new ApplicationUser()
{
Email = "maria.rodriguez@contoso.com",
FullName = "Maria Rodriguez"
};
//}
//else
//{
// return null;
//}
} [HttpPost]
public async Task<IActionResult> Login(LoginViewModel loginViewModel, string returnUrl = null)
{
if (!ModelState.IsValid)
{
return Content("validation fail");
}
var user = await AuthenticateUser(loginViewModel.UserName, loginViewModel.Password);
if (user == null)
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View();
}
ViewData["ReturnUrl"] = returnUrl; var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Email),
new Claim("FullName", user.FullName),
new Claim(ClaimTypes.Role, "Administrator"),
}; var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed. //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie. //IsPersistent = true,
// Whether the authentication session is persisted across
// multiple requests. When used with cookies, controls
// whether the cookie's lifetime is absolute (matching the
// lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued. //RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
}; await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties); if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return Redirect("/");
}
} public IActionResult AccessDenied(string returnUrl = null)
{
return View();
} public async Task<IActionResult> Logout()
{
#region snippet1
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
#endregion return Redirect("/");
}
}

上面的代码即包含“登录”方法,又包含登出方法。

await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);

关于 Claim, ClaimsIdentity, ClaimsPrincipal,读者如果有疑问,可以参考文章 理解ASP.NET Core验证模型(Claim, ClaimsIdentity, ClaimsPrincipal)不得不读的英文博文

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

MyClaims.cshtml

@using Microsoft.AspNetCore.Authentication

<h2>HttpContext.User.Claims</h2>

<dl>
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
</dl> <h2>AuthenticationProperties</h2> <dl>
@{
var taskAuth = await Context.AuthenticateAsync();
}
@if(taskAuth != null && taskAuth.Properties != null && taskAuth.Properties.Items != null)
{
@foreach (var prop in taskAuth.Properties.Items)
{
<dt>@prop.Key</dt>
<dd>@prop.Value</dd>
}
}
else
{
<dt>no data.</dt>
}
</dl>

运行截图

1. 没有登录的情况下

2. 登录界面

3. 登录成功

谢谢浏览!

ASP.NET Core 如何用 Cookie 来做身份验证的更多相关文章

  1. Asp.Net Core 5 REST API 使用 JWT 身份验证 - Step by Step

    翻译自 Mohamad Lawand 2021年1月22日的文章 <Asp Net Core 5 Rest API Authentication with JWT Step by Step> ...

  2. ASP.NET CORE中使用Cookie身份认证

    大家在使用ASP.NET的时候一定都用过FormsAuthentication做登录用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cook ...

  3. 在ASP.NET Core 中使用Cookie中间件

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  4. 在ASP.NET Core 中使用Cookie中间件 (.net core 1.x适用)

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  5. 如何在ASP.NET Core中实现一个基础的身份认证

    注:本文提到的代码示例下载地址> How to achieve a basic authorization in ASP.NET Core 如何在ASP.NET Core中实现一个基础的身份认证 ...

  6. [转]如何在ASP.NET Core中实现一个基础的身份认证

    本文转自:http://www.cnblogs.com/onecodeonescript/p/6015512.html 注:本文提到的代码示例下载地址> How to achieve a bas ...

  7. ASP.NET Core WebApi基于JWT实现接口授权验证

    一.ASP.Net Core WebApi JWT课程前言 我们知道,http协议本身是一种无状态的协议,而这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,那么下一次请求时,用户还要再 ...

  8. 使用ASP.NET Identity 实现WebAPI接口的Oauth身份验证

    使用ASP.NET Identity 实现WebAPI接口的Oauth身份验证   目前WEB 前后端分离的开发模式比较流行,之前做过的几个小项目也都是前后分离的模式,后端使用asp.net weba ...

  9. asp.net core 2.0 cookie的使用

    本文假设读者已经了解cookie的概念和作用,并且在传统的.net framework平台上使用过. cookie的使用方法和之前的相比也有所变化.之前是通过cookie的add.set.clear. ...

随机推荐

  1. appium---模拟点击事件

    在做自动化的过程中都会遇到一些无法定位到的地方,或者通过元素怎么都定位不成功的地方,这个时候我们可以使用必杀技,通过坐标定位.具体的怎么操作呢? swipe点击事件 前面安静写过一篇关于swipe的滑 ...

  2. 搭建Harbor

    搭建Harbor 一.安装准备 二.安装docker-ce 三.安装docker-compose 四.安装harbor 5.1下载安装程序 5.2配置harbor.yml 5.3运行install.s ...

  3. 体感在js中的调用

    体感技术,在于人们可以很直接地使用肢体动作,与周边的装置或环境互动,而无需使用任何复杂的控制设备,便可让人们身临其境地与内容做互动. 体感分为三大类: 惯性感测:主要是以惯性传感器为主,例如用重力传感 ...

  4. 传统jdbc存在的问题总结

    1.数据库连接创建.释放频繁造成系统资源浪费,影响系统性能,可使用数据库连接池解决此问题. 2.sql语句中在代码中硬编码,代码不易维护,sql变动需要改变java代码. 3.使用preparedSt ...

  5. 一种简单实现Redis集群Pipeline功能的方法及性能测试

    上一篇文章<redis pipeline批量处理提高性能>中我们讲到redis pipeline模式在批量数据处理上带来了很大的性能提升,我们先来回顾一下pipeline的原理,redis ...

  6. MVC过滤器:过滤器执行顺序

    如果某个Action过滤器运用了多种过滤器,那么过滤器的执行顺序是如何呢? 规则一:不同类型的过滤器有一个先后顺序 即执行顺序是:授权过滤器->动作过滤器->结果过滤器->异常过滤器 ...

  7. [Abp vNext 源码分析] - 5. DDD 的领域层支持(仓储、实体、值对象)

    一.简要介绍 ABP vNext 框架本身就是围绕着 DDD 理念进行设计的,所以在 DDD 里面我们能够见到的实体.仓储.值对象.领域服务,ABP vNext 框架都为我们进行了实现,这些基础设施都 ...

  8. Java的三种代理模式&完整源码分析

    Java的三种代理模式&完整源码分析 参考资料: 博客园-Java的三种代理模式 简书-JDK动态代理-超详细源码分析 [博客园-WeakCache缓存的实现机制](https://www.c ...

  9. 微信小程序新服务消息推送 —— 订阅消息

    微信团队前不久公测了「订阅消息」,原有的小程序模板消息接口将于 2020 年 1 月 10 日下线,届时将无法发送模板消息.「订阅消息」将完全替代「模板消息」,这两天得空测试了一波. 1.下发权限机制 ...

  10. 在标准实体特殊消息上注册插件及Dynamics CRM 2015中计算字段的使用

    关注本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复157或者20151005可方便获取本文,同时可以在第一时间得到我发布的最新的博文信息,follow me! 前面的 插件系列博客教程 讲述了 ...