ASP.Net Core 2.1+ Cookie 登录授权验证【简单Cookie验证】
介绍
***本文章发布于博客园:https://www.cnblogs.com/fallstar/p/11310749.html ***
作者:fallstar
本文章适用于:ASP.NET Core 2.1 +
今天想给一个asp.net core 的项目加上权限验证,于是研究了一下怎么加,
折腾了好一阵,发现原来Filter的方式被放弃了,现在使用Policy 和 Scheme 的方式来校验了。。。
然后开始猛查 msdn 和 stackoverflow ,然而。。。找到的都不合适,我就要简单容易的。。。
因为如果能直接用 AllowAnonymous和Authorize 可以省事好多的。
参照了 msdn ,有了第一版:
//Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.LoginPath = new PathString("/Home/Login");//登录页面
x.LogoutPath = new PathString("/Home/Logout");//登出页面
});
}
//HomeController .cs
/// <summary>
/// 首页
/// </summary>
[Authorize]
public class HomeController : Controller
{
/// <summary>
/// 首页
/// </summary>
/// <returns></returns>
public IActionResult Index()
{
return View();
}
/// <summary>
/// 登录
/// </summary>
/// <returns></returns>
[AllowAnonymous]
public IActionResult Login()
{
return View();
}
/// <summary>
/// 登出
/// </summary>
/// <returns></returns>
public IActionResult Logout()
{
HttpContext.SignOutClain();
return RedirectToAction("Login");
}
}
上面的代码很简单,就用于授权跳转,Index是首页需要权限,Login可以匿名访问。
接着是用于提供拓展方法的WebHelper
直接在控制器的Action 里面调用 HttpContext.Login 就可以了。
/// <summary>
/// Web帮助类
/// </summary>
public static class WebHelper
{
#region Auth
/// <summary>
/// 登录
/// </summary>
public static bool Login(this HttpContext context, string username,string password)
{
//验证登录
if (!(username != "admin" && password != "123456"))
return false;
//成功就写入
context.SignInClain(1, username, true, TimeSpan.FromHours(3));
return true;
}
/// <summary>
/// 将登录用户信息写入凭据,输出到cookie
/// </summary>
/// <param name="context"></param>
/// <param name="userid"></param>
/// <param name="username"></param>
/// <param name="isAdmin"></param>
public static async void SignInClain(this HttpContext context, int userid, string username, bool isAdmin = false, TimeSpan? expire = null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username),
new Claim(ClaimTypes.NameIdentifier,userid.ToString()),
new Claim(ClaimTypes.Role,isAdmin?"1":"0")
};
if (!expire.HasValue)
expire = TimeSpan.FromHours(3);
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties()
{
ExpiresUtc = DateTime.UtcNow.Add(expire.Value),
IsPersistent = true,
};
await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
}
/// <summary>
/// 登出,清除登录信息
/// </summary>
/// <param name="context"></param>
public static async void SignOutClain(this HttpContext context)
{
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
}
#endregion
}
当我以为完事的时候。。。突然发现webapi也被带到 登录页面去了。。。这肯定是不行的。
接着我有苦苦研究文档,没有收获,最后,我仔细的查看配置项里面的类,然后找到了办法。
最终版就是下面这段了:
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.Lax;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x =>
{
x.LoginPath = new PathString("/Home/Login");//登录页面
x.LogoutPath = new PathString("/Home/Logout");//登出页面
//多了下面这段针对WebApi的代码
x.Events.OnRedirectToLogin = z =>
{
if (z.HttpContext.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
{
z.HttpContext.Response.Redirect("/api/Login/UnAuth");//未授权错误信息的接口地址,返回json
}
else
{
z.HttpContext.Response.Redirect(z.RedirectUri);//其它安装默认处理
}
return Task.CompletedTask;
};
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseCookiePolicy();
app.UseAuthentication();
//app.UseMvc
}
OK大吉告成了~~
ASP.Net Core 2.1+ Cookie 登录授权验证【简单Cookie验证】的更多相关文章
- Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- net core体系-web应用程序-4asp.net core2.0 项目实战(1)-12基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- 【ASP.NET Core】运行原理(4):授权
本系列将分析ASP.NET Core运行原理 [ASP.NET Core]运行原理(1):创建WebHost [ASP.NET Core]运行原理(2):启动WebHost [ASP.NET Core ...
- ASP.NET Core策略授权和 ABP 授权
目录 ASP.NET Core 中的策略授权 策略 定义一个 Controller 设定权限 定义策略 存储用户信息 标记访问权限 认证:Token 凭据 颁发登录凭据 自定义授权 IAuthoriz ...
- asp.net Core 中AuthorizationHandler 实现自定义授权
前言 ASP.NET Core 中 继承的是AuthorizationHandler ,而ASP.NET Framework 中继承的是AuthorizeAttribute. 它们都是用过重写里面的方 ...
- 第十五节:Asp.Net Core中的各种过滤器(授权、资源、操作、结果、异常)
一. 简介 1. 说明 提到过滤器,通常是指请求处理管道中特定阶段之前或之后的代码,可以处理:授权.响应缓存(对请求管道进行短路,以便返回缓存的响应). 防盗链.本地化国际化等,过滤器用于横向处理业务 ...
- Asp.Net Core Identity 完成注册登录
Identity是Asp.Net Core全新的一个用户管理系统,它是一个完善的全面的庞大的框架,提供的功能有: 创建.查询.更改.删除账户信息 验证和授权 密码重置 双重身份认证 支持扩展登录,如微 ...
- asp.net core 控制静态文件的授权
静态文件访问在网站中是一项重要的服务,用于向前端提供可以直接访问的文件,如js,css,文档等,方法是在Startup的Configure中添加UseStaticFiles()管道. 参考:ASP.N ...
- ASP.NET Core 实现跨站登录重定向的新姿势
作为 .NET 程序员,痛苦之一是自从 ASP.NET 诞生之日起直到最新的 ASP.NET Core 都无法直接实现跨站登录重定向(比如访问 https://q.cnblogs.com ,跳转到 h ...
随机推荐
- mysql regexp 表达式
mysql> select * from test; +----+----------+-------+-----------+ | id | name | score | subject | ...
- 辨析Java方法参数中的值传递和引用传递
小方法大门道 小瓜瓜作为一个Java初学者,今天跟我说她想通过一个Java方法,将外部变量通过参数传递到方法中去,进行逻辑处理,方法执行完毕之后,再对修改过的变量进行判断处理,代码如下所示. publ ...
- elastic stack安装运行(docker)
https://www.docker.elastic.co 注:目前阿里云为7.4 elasticsearch 参考https://www.elastic.co/guide/en/elasticsea ...
- v-if和v-for一起使用的几个方法
方法一(推荐): 不带if <ul> <li v-for="(item, index) in list" :key="index" > ...
- PostgreSQL中的The Oversized-Attribute Storage Technique(TOAST:超大属性存储技术)
PostgreSQL使用固定的页面大小(通常为8kB),并且不允许元组跨越多个页面.因此,不可能直接存储非常大的字段值.为了克服这种限制,将大字段值压缩和/或分解成多个物理行.这对用户来说是透明的,对 ...
- ISO/IEC 9899:2011 条款6.10.1——条件包含
6.10.1 条件包含 约束 1.控制条件包含的表达式应该是一个整数常量表达式,除了:标识符(包括那些词法上与关键字相同的)被解析为以下所描述的:[注:因为控制常量表达式在翻译阶段4期间被计算,所以所 ...
- redis的相关原理
一.AOF 二.RDB 三.哨兵
- oracle plsql 异常
set serveroutput on DECLARE pename emp.ename%type; begin '; exception when no_data_found then dbms ...
- NI MAX中缺少串口(转)
Software Measurement & Automation Explorer (MAX) Driver NI-VISA 问题详述 在NI MAX中,设备和接口中的串口不可用或缺 ...
- java:网络编程(UDP (DatagramSocket和DatagramPacket)正则表达式)
java:网络编程(UDP (DatagramSocket和DatagramPacket)正则表达式) * TCP* 特点:面向连接,点对点的通信,效率较低,但安全可靠* UDP:用户数据报协议,类似 ...