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 ...
随机推荐
- Intellij IDEA 自动清除无效 import 和 清除无效 import 的快捷键
可以settings-general-auto import-java项,勾选optimize imports on the fly,在当前项目下会自动清除无效的import,而且这个是随时自动清除的 ...
- rsync实时同步
假设有如下需求: 假设两个服务器: 192.168.0.1 源服务器 有目录 /opt/test/ 192.168.0.2 目标服务器 有目录 /opt/bak/test/ 实现的目的就是保持这两 ...
- 前后端通信—CORS(支持跨域)
根据前端跨域的那些事这篇文章中的跨域的理解这一块,我们重新创建两个服务,第一个服务使用了test.html const http = require('http') const fs = requir ...
- Real-time ‘Actor-Critic’ Tracking
Real-time ‘Actor-Critic’ Tracking 2019-07-15 10:49:16 Paper: http://openaccess.thecvf.com/content_EC ...
- spring入门篇
- 一款阿里开源的 Java 诊断工具
Arthas是什么鬼? Arthas是一款阿里巴巴开源的 Java 线上诊断工具,功能非常强大,可以解决很多线上不方便解决的问题. Arthas诊断使用的是命令行交互模式,支持JDK6+,Linux. ...
- Java并发包之阶段执行之CompletionStage接口
前言 CompletionStage是Java8新增得一个接口,用于异步执行中的阶段处理,其大量用在Lambda表达式计算过程中,目前只有CompletableFuture一个实现类,但我先从这个接口 ...
- python开发--列表当全局变量来使用
python中,申明全局变量的时候,一般该变量类型基本上是:字符串或数字: 比较少用“列表”当做变量, 当有作用域限制的情况下,想要外部调用内部作用域的“列表”变量时,可以用这种方式,外部申明一个空列 ...
- [译]Pandas列数据展示不全解决方法?
Pandas数据展示列太多会显示...不显示具体数据. 设置参数可以显示全部数据: pd.set_option('display.expand_frame_repr', False)
- [LeetCode] 117. Populating Next Right Pointers in Each Node II 每个节点的右向指针 II
Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...