一、Core的授权

配置

打开项目中的Startup.cs文件,找到ConfigureServices方法,我们通常在这个方法里面做依赖注入的相关配置。添加如下代码:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Account/Login");
o.AccessDeniedPath = new PathString("/Error/Forbidden");
});
}

这段代码的大概意思就是,添加授权支持,并添加使用Cookie的方式,配置登录页面和没有权限时的跳转页面。

再找到Configure方法,添加 app.UseAuthentication(),使用授权:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseAuthentication();
}

登录

添加一个Controller,如AccountController,再添加一个Action,如 Login,所配置的路由,要与上面的配置对应,不然跳转登录时会跳错页面。

用户提交用户名和密码,登录代码大致如下:

[HttpPost]
public async Task <IActionResult> Login(string userName, string password, string ReturnUrl)
{
var user = _userService.Login(userName, password);
if (user != null)
{ user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
var identity = new ClaimsIdentity(user);
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserID));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity)); if (ReturnUrl.IsNullOrEmpty())
{
return RedirectToAction("Index", "Dashboard");
}
return Redirect(ReturnUrl);
}
ViewBag.Errormessage = "登录失败,用户名密码不正确";
return View();
}

这里要注意的是 AuthenticationType 所设置的Scheme一定要与前面的配置一样,这样对应的登录授权才会生效。

二、使用登录身份

登录的目录,就是希望有些页面或者资源只有登录以后才可访问。使用AuthorizeAttribute来做限制。在需要做限制的Controller上加上[Authorize]特性来做限制。

[Authorize]
public class ThemeController
{
}

这样这个Controller下的所有的Action都必需要登录后才可访问。如果希望其中某些Action可以不用登录也可访问,可以添加例外:

[AllowAnonymous]
public ActionResult Index()
{
return View();
}

到这里一个最基础的登录就完成了。

在Web项目中,通常会遇到一个问题,后端管理员和前台用户。这两个用户都是可登录的,在 .net core 2.0,这个将很容易实现。

三、多用户登录

添加一个登录方案(Scheme)

CookieAuthenticationDefaults.AuthenticationScheme,这是系统已经定义好的一个默认的登录方案,添加一个新的来实现一个不同的身份登录。代码如下:

public class CustomerAuthorizeAttribute : AuthorizeAttribute
{
public const string CustomerAuthenticationScheme = "CustomerAuthenticationScheme";
public CustomerAuthorizeAttribute()
{
this.AuthenticationSchemes = CustomerAuthenticationScheme;
}
}

添加使用这个新的方案,在Startup.cs文件下:

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Account/Login");
o.AccessDeniedPath = new PathString("/Error/Forbidden");
})
.AddCookie(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, option =>
{
option.LoginPath = new PathString("/Account/Signin");
option.AccessDeniedPath = new PathString("/Error/Forbidden");
});
}

添加新的登录方案,并配置一个新的登录页面,登录的方法和刚才是一样,只是AuthenticationType使用了新的方案。

[HttpPost]
public async Task <IActionResult> Login(string userName, string password, string ReturnUrl)
{
var user = _userService.Login(userName, password);
if (user != null)
{ user.AuthenticationType = CustomerAuthorizeAttribute.CustomerAuthenticationScheme;
var identity = new ClaimsIdentity(user);
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserID));
await HttpContext.SignInAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, new ClaimsPrincipal(identity)); if (ReturnUrl.IsNullOrEmpty())
{
return RedirectToAction("Index", "Dashboard");
}
return Redirect(ReturnUrl);
}
ViewBag.Errormessage = "登录失败,用户名密码不正确";
return View();
}

验证登录状态

使用方法和之前的差不多,换成新的CustomerAuthorizeAttribute就行了

[CustomerAuthorize]
public class CustomerController
{
}

CustomerAuthorizeAttribute这个类,不是必需的,只是为了方便使用而写,其实完全可以只定义一个新的方案(Scheme)就行了。

谁才是HttpContext.User?

登录了多个用户,那么谁才是HttpContext.User呢?如果你的Controller或者Action上有使用AuthorizeAttribute,那这个Attribute使用的登录方案是哪个,则这个HttpContext.User对应的就是那个方案的登录用户。如果没有使用,则AddAuthentication()方法默认指它的方案(Scheme)所登录的用户,就是这个HttpContext.User了。

如何获取对应方案的登录用户呢?使用HttpContext.AuthenticateAsync

var auth = await HttpContext.AuthenticateAsync(CustomerAuthorizeAttribute.CustomerAuthenticationScheme);
if (auth.Succeeded)
{
auth.Principal.Identity...
}

退出登录

这个就简单了,指定方案退出就可以了。

public async Task Logout(string returnurl)
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect(returnurl ?? "~/");
}

一、Core授权(基于cookie)的更多相关文章

  1. .Net Core MVC 基于Cookie进行用户认证

    在打代码之前先说一下思路. 登录的的时候服务端生成加密的字符串(用户名.id.当前时间)并且存入客户端cookie中,服务端的缓存中.对客户端的每次请求进行拦截,解密保存在cookie中的加密字符串. ...

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

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

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

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

  4. ASP.NET Core WebApi基于JWT实现接口授权验证

    一.ASP.Net Core WebApi JWT课程前言 我们知道,http协议本身是一种无状态的协议,而这就意味着如果用户向我们的应用提供了用户名和密码来进行用户认证,那么下一次请求时,用户还要再 ...

  5. ASP.NET Core Authentication系列(四)基于Cookie实现多应用间单点登录(SSO)

    前言 本系列前三篇文章分别从ASP.NET Core认证的三个重要概念,到如何实现最简单的登录.注销和认证,再到如何配置Cookie 选项,来介绍如何使用ASP.NET Core认证.感兴趣的可以了解 ...

  6. 理解ASP.NET Core - 基于Cookie的身份认证(Authentication)

    注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 概述 通常,身份认证(Authentication)和授权(Authorization)都会放 ...

  7. Asp.Net Core基于Cookie实现同域单点登录(SSO)

    在同一个域名下有很多子系统 如:a.giant.com  b.giant.com   c.giant.com等 但是这些系统都是giant.com这个子域. 这样的情况就可以在不引用其它框架的情况下, ...

  8. 实践剖析.NET Core如何支持Cookie和JWT混合认证、授权

    前言 为防止JWT Token被窃取,我们将Token置于Cookie中,但若与第三方对接,调用我方接口进行认证.授权此时仍需将Token置于请求头,通过实践并联系理论,我们继续开始整活!首先我们实现 ...

  9. ASP.NET Core WebApi基于Redis实现Token接口安全认证

    一.课程介绍 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebSer ...

  10. .NET CORE 授权

    .NET CORE 授权 一.三种方式授权 不论使用NET CORE框架的何种授权都必须引入中间件,因为它实现了在管道中对当前请求的鉴权和授权的验证,在Startup中的Configure中首先加入鉴 ...

随机推荐

  1. What is the !! (not not) operator in JavaScript?

    What is the !! (not not) operator in JavaScript? 解答1 Coerces强制 oObject to boolean. If it was falsey ...

  2. 一、基础篇--1.1Java基础-MVC设计思想

    MVC简介: MVC(Model View Controller) 是模型(model)-视图(view)-控制器(controller)的缩写.一种软件设计典范,用一种业务逻辑.数据.界面显示分离的 ...

  3. Dark 数据类型

     dark基础数据类型  1数值型 num int a =1; double b=1.0; 2 字符型 string a ='hello'; 插值表达式${expression} int a = 1; ...

  4. 深度学习基础——Epoch、Iteration、Batchsize

    原文地址:https://www.cnblogs.com/Johnny-z6951/p/11201081.html 梯度下降是一个在机器学习中用于寻找较佳结果(曲线的最小值)的迭代优化算法.梯度的含义 ...

  5. JAVA基础面试汇总

    一.基础知识:1.JVM.JRE和JDK的区别:    JVM(Java Virtual Machine):java虚拟机,用于保证java的跨平台的特性.                  java ...

  6. 微信小程序---交互反馈

    1.学习大纲: 2.showToast(): wx.showToast({ title: '成功', icon: 'success', duration: }) 3.hieToast(): wx.sh ...

  7. java:Mybatis框架3(二级缓存,延时和积极加载,SSI(Ibatis)集成,SSM集成)

    1.二级缓存: 需要导入二级缓存jar包: mybatis03: ehcache.xml: <ehcache xmlns:xsi="http://www.w3.org/2001/XML ...

  8. java:Oracle(Jdbc的封装)和HTML(登录,注册,个人信息界面)

    1.Oracle Jdbc的封装: public class TestJdbc { // 把jdbc需要的属性,全部私有化 private static final String DRIVER = & ...

  9. OpenCV 中获取图像或矩阵最大、最小值的简便方法

    C++: void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc ...

  10. LeetCode.917-只反转字母(Reverse Only Letters)

    这是悦乐书的第353次更新,第378篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第215题(顺位题号是917).给定一个字符串S,返回"反向"字符串 ...