前言

本示例完全是基于 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. 电位器控制两个 LED 灯交替闪烁

    电路图: 布局:

  2. [读论文]Shading-aware multi view stereo

    如何实现refine的? 几何误差和阴影误差如何加到一起? 为了解决什么问题? 弱纹理或无纹理:单纯的多视图立体算法在物体表面弱纹理或者无纹理区域重建完整度不够高,精度也不够高,因此结合阴影恢复形状来 ...

  3. idea创建maven工程

    1.右键更目录,new->Module 2.选择Maven,并配置自己的SDK,一般默认的也可以用,点击next进入下一步 3.配置pom文件里的GroupId和Artifactld 4.配置m ...

  4. Mybatis基本类型参数非空判断(异常:There is no getter for property...)

    先看一小段代码 <select id="queryByPhone" parameterType="java.lang.String" resultType ...

  5. 【xAsset框架】HFS 轻量级HTTP Server快速入门指南

    一.引子 最近马三有幸参与开发了一个简易轻量的Unity资源管理框架 xAsset ,xasset 提供了一种使用资源路径的简单的方式来加载资源,简化了Unity项目资源打包,更新,加载,和回收的作业 ...

  6. ETCD:运行时重新配置

    原文地址:runtime reconfiguration etcd带有增量运行时重新配置的支持.允许我们在集群运行的时候更新集群成员关系. 仅当大多数集群成员都在运行时,才能处理重新配置请求,强烈建议 ...

  7. C++ 课程设计——电梯调度系统

    这是我在本学期C++课程最后的课程设计报告,源代码将会上传到GitHub上. 一.背景 随着经济的不断发展,越来越多的摩天大楼拔地而起,而电梯作为高层建筑物种的运送人员货物的设备也越来越被广泛使用.电 ...

  8. C#面向对象--简介

    一.C#提供对面向对象编程(Object Oriented Programming)的完整支持:类描述对象的类型,而对象是类的具体实例,创建对象的过程也被称为实例化(Instantiation):通常 ...

  9. RabbitMQ的第一次亲密接触

    企业应用系统,如果系统之间的通信.集成与整合,尤其当面临异构系统时,那么需要分布式的调用与通信.系统中一般会有很多对实时性要求不高但零零碎碎且耗时的地方,比如发送短信,邮件提醒,记录用户操作日志等,在 ...

  10. JS中的call,apply和bind及记忆方式

    总结 call().apply()和bind()都是用来改变函数执行时的上下文,可借助它们实现继承:call()和apply()唯一区别是参数不一样,call()是apply()的语法糖:bind() ...