以admin控制器为要认证的控制器举例

1.对控制器设置权限特性

//a 认证命名空间
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; namespace CookieBasedAuth.Controllers
{
//b 认证特性
[Authorize]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
}
}

在加了Authorize特性之后,访问admin控制器的index方法,页面会显示异常,异常告诉我们,没有指定认证框架,它不知道如何来认证挑战

2.为程序注入Cookie认证框架

a.首先要引入两个程序集

//1 为了Cookie认证证明 引入的以下两个命名空间  认证命名空间 和 认证Cookie命名空间
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;

认证和cookie框架命名空间的引入

b.在服务中注入认证

 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;
});
//2 CookieAuthenticationDefaults.AuthenticationScheme的值是一个字符串常量 "Cookies"
//AddAuthentication 方法要求传入的是一个字符串 我传入的字符串是Cookies 就是说 使用Cookie 认证
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

注入cookie认证

此时再访问admin控制器的index方法,已经不报异常了,而是直接跳转到account/login

http://localhost:60208/Account/Login?ReturnUrl=%2Fadmin

3.创建Account控制器 在此不挑战,直接授予权限

//引入认证相关的命名空间
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
//引入安全相关的命名空间
using System.Security.Claims; namespace CookieBasedAuth.Controllers
{
public class AccountController : Controller
{
public IActionResult Login()
{
var claims = new List<Claim>{
new Claim(ClaimTypes.Name,"应龙"),
new Claim(ClaimTypes.Role,"国王")
};
//千万要注意下面的new ClaimsIdentity的构造函数,第二个参数要指明认证框架,要和服务中注入的框架一致 都是cookie
var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity));
return Ok();
}
}
}

授权

即便授权了,我们请求admin控制器的index方法,会跳转到account控制器的login方法。按想象的此时授权了,就应该可以访问admin控制器的index了,然而我们会发现没有用,也就是说没有授权,还是会跳转到account/login

4.将cookie验证加入到中间件

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
} app.UseStaticFiles();
app.UseCookiePolicy(); //将认证中间件弄进来 使得我们的请求会进入认证管道
app.UseAuthentication(); app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

将认证授权加入到中间件

完成 !

在asp.net core中使用cookie认证的更多相关文章

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

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

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

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

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

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

  4. ASP.NET Core 中的那些认证中间件及一些重要知识点

    前言 在读这篇文章之间,建议先看一下我的 ASP.NET Core 之 Identity 入门系列(一,二,三)奠定一下基础. 有关于 Authentication 的知识太广,所以本篇介绍几个在 A ...

  5. [转]ASP.NET Core 中的那些认证中间件及一些重要知识点

    本文转自:http://www.qingruanit.net/c_all/article_6645.html 在读这篇文章之间,建议先看一下我的 ASP.NET Core 之 Identity 入门系 ...

  6. 如何简单的在 ASP.NET Core 中集成 JWT 认证?

    前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...

  7. ASP.NET Core 中jwt授权认证的流程原理

    目录 1,快速实现授权验证 1.1 添加 JWT 服务配置 1.2 颁发 Token 1.3 添加 API访问 2,探究授权认证中间件 2.1 实现 Token 解析 2.2 实现校验认证 1,快速实 ...

  8. asp.net core中使用cookie身份验证

    配置 在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务: services.AddAuth ...

  9. 在ASP.NET Core中添加的Cookie如果含有特殊字符,会被自动转义

    我们知道在Cookie中有些字符是特殊字符,这些字符是不能出现在Cookie的键值中的. 比如"="是Cookie中用来分隔键和值的特殊字符,例如:Key01=Value01,表示 ...

随机推荐

  1. SpringBoot错误信息总结(不定时更新)

    1." java.lang.IllegalStateException: @Bean method ShiroConfig.cacheManager called as a bean ref ...

  2. HIVE快速入门 分类: B4_HIVE 2015-06-06 11:27 59人阅读 评论(0) 收藏

    (一)简单入门 1.创建一个表 create table if not exists ljh_emp( name string, salary float, gender string) commen ...

  3. [Angular] Separating Structural Styles From Theme Styles - Making Components Themeable

    For the component's css file, we can improt two css files: common.css default-theme.css @import &quo ...

  4. [TypeStyle] Add responsive styles using TypeStyle Media Queries

    Media queries are very important for designs that you want to work on both mobile and desktop browse ...

  5. centos 查询DNS

    cat  /etc/resolv.conf

  6. [Vue] Build Vue.js Apps with the Vue-CLI and Nuxt.js

    The vue-cli allows you to easily start up Vue projects from the command line while Nuxt.js enables a ...

  7. 设置secureCRT中vim的字体颜色 分类: B3_LINUX 2014-07-12 22:01 1573人阅读 评论(0) 收藏

    1.在/etc/vimrc新增以下一行 syntax on 注:上述方法对root用户无效,原因为在一般用户中,alias vi=vim,而在root用户中默认无此设置,因此若需要root用户也显示颜 ...

  8. MouseGestureL.ini shift up/down/left/right edge

    MouseGestureL.ini [ShiftPress]Icon=C:\Windows\System32\explorer.exe,6Custom=GetKeyState("Shift& ...

  9. 判断文件是否存在的另一种方法 _access 和 _waccess

    函数原型: int _access( const char *path, int mode ); int _waccess( const wchar_t *path, int mode ); 示例代码 ...

  10. 【u032】均衡发展

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 神牛小R在许多方面都有着很强的能力,具体的说,他总共有m种能力,并将这些能力编号为1到m.他的能力是一 ...