介绍

***本文章发布于博客园:https://www.cnblogs.com/fallstar/p/11310749.html ***

作者:fallstar

本文章适用于:ASP.NET Core 2.1 +

今天想给一个asp.net core 的项目加上权限验证,于是研究了一下怎么加,

折腾了好一阵,发现原来Filter的方式被放弃了,现在使用Policy 和 Scheme 的方式来校验了。。。

然后开始猛查 msdn 和 stackoverflow ,然而。。。找到的都不合适,我就要简单容易的。。。

因为如果能直接用 AllowAnonymousAuthorize 可以省事好多的。

参照了 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验证】的更多相关文章

  1. Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  2. net core体系-web应用程序-4asp.net core2.0 项目实战(1)-12基于cookie登录授权认证并实现前台会员、后台管理员同时登录

    1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...

  3. 【ASP.NET Core】运行原理(4):授权

    本系列将分析ASP.NET Core运行原理 [ASP.NET Core]运行原理(1):创建WebHost [ASP.NET Core]运行原理(2):启动WebHost [ASP.NET Core ...

  4. ASP.NET Core策略授权和 ABP 授权

    目录 ASP.NET Core 中的策略授权 策略 定义一个 Controller 设定权限 定义策略 存储用户信息 标记访问权限 认证:Token 凭据 颁发登录凭据 自定义授权 IAuthoriz ...

  5. asp.net Core 中AuthorizationHandler 实现自定义授权

    前言 ASP.NET Core 中 继承的是AuthorizationHandler ,而ASP.NET Framework 中继承的是AuthorizeAttribute. 它们都是用过重写里面的方 ...

  6. 第十五节:Asp.Net Core中的各种过滤器(授权、资源、操作、结果、异常)

    一. 简介 1. 说明 提到过滤器,通常是指请求处理管道中特定阶段之前或之后的代码,可以处理:授权.响应缓存(对请求管道进行短路,以便返回缓存的响应). 防盗链.本地化国际化等,过滤器用于横向处理业务 ...

  7. Asp.Net Core Identity 完成注册登录

    Identity是Asp.Net Core全新的一个用户管理系统,它是一个完善的全面的庞大的框架,提供的功能有: 创建.查询.更改.删除账户信息 验证和授权 密码重置 双重身份认证 支持扩展登录,如微 ...

  8. asp.net core 控制静态文件的授权

    静态文件访问在网站中是一项重要的服务,用于向前端提供可以直接访问的文件,如js,css,文档等,方法是在Startup的Configure中添加UseStaticFiles()管道. 参考:ASP.N ...

  9. ASP.NET Core 实现跨站登录重定向的新姿势

    作为 .NET 程序员,痛苦之一是自从 ASP.NET 诞生之日起直到最新的 ASP.NET Core 都无法直接实现跨站登录重定向(比如访问 https://q.cnblogs.com ,跳转到 h ...

随机推荐

  1. restframework之节流

    基本思路(原生Django而言): 在django2.x中,若出现节流(访问频率控制)的需求,我们首先想到的是使用一个字典(dict类型)来存储所有IP地址的访问时间记录,这是针对于匿名用户(IP)而 ...

  2. h5的复制功能的使用,Clipboard.js的使用,主要是在app里面使用

    app中使用,框架用的是vue.js 1.显示要下载这个Clipboard.js插件 package-lock.json里面 "clipboard-polyfill": { &qu ...

  3. MongoDB 数据库创建删除

    在MongoDB数据库里面是存在有数据库的概念,但是没有模式(所有的信息都是按照文档保存的),保存数据的结构就是JSON结构,只不过在进行一些数据处理的时候才会使用到MongoDB自己的一些操作符号 ...

  4. docker容器启动后添加端口映射

    DOCKER 给运行中的容器添加映射端口 方法1 1.获得容器IP 将container_name 换成实际环境中的容器名 docker inspect `container_name` | grep ...

  5. ArrayList: java之ArrayList详细介绍(转)

    1  ArrayList介绍 ArrayList简介 ArrayList 是一个数组队列,相当于 动态数组.与Java中的数组相比,它的容量能动态增长.它继承于AbstractList,实现了List ...

  6. PG11开启WAL归档

    -创建归档目录 mkdir -p $PGDATA/archive_wals chown -R postgres.postgres $PGDATA/archive_wals -修改参数(在配置文件中配置 ...

  7. 筛选出dataframe中全为数字的列的值

    In [1]: import pandas as pd In [2]: import numpy as np In [3]: students = [ ('jack', 'Apples' , 34) ...

  8. tomcat常见报错解决方法汇总

    报错一:内存泄漏,字眼This is very likely to create a memory leak. 解决方法:修改tomcat内存. 在tomcat/bin目录下,修改catalina.s ...

  9. RSA 系统找不到指定的文件

    未测试 System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); 改为 C ...

  10. mysql执行计划详解,

    一.语法 explain SQL语句 例如: explain ; 二.explain输出解释 +----+-------------+-------+-------+----------------- ...