一、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. 使用stringstream代替sprintf和sscanf

    C++里面的字符串格式话 之前一直是用的sprintf和sscanf 比较麻烦的是要申请一个字符数组然后在调用 用stringstream就比较完美 int main(int narg,char** ...

  2. C#的语音识别 using System.Speech.Recognition;

    using System; using System.Collections.Generic; using System.Linq; using System.Speech.Recognition; ...

  3. MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications

    1. 摘要 作者提出了一系列应用于移动和嵌入式视觉的称之为 MobileNets 的高效模型,这些模型采用深度可分离卷积来构建轻量级网络. 作者还引入了两个简单的全局超参数来有效地权衡时延和准确率,以 ...

  4. 深入解析CNN pooling 池化层原理及其作用

    原文地址:https://blog.csdn.net/CVSvsvsvsvs/article/details/90477062 池化层作用机理我们以最简单的最常用的max pooling最大池化层为例 ...

  5. Tensorflow Lite tflite模型的生成与导入

    假如想要在ARM板上用tensorflow lite,那么意味着必须要把PC上的模型生成tflite文件,然后在ARM上导入这个tflite文件,通过解析这个文件来进行计算. 根据前面所说,tenso ...

  6. vtkTestHull将多个平面围成一个凸面体

    1.vtkHull produce an n-sided convex hull vtkHull is a filter which will produce an n-sided convex hu ...

  7. python 并发编程 多线程 GIL与Lock

    GIL与Lock Python已经有一个GIL来保证同一时间只能有一个线程来执行了,为什么这里还需要互斥锁lock? 锁的目的是为了保护共享的数据,同一时间只能有一个线程来修改共享的数据 GIT保证了 ...

  8. C语言Ⅰ博客作业05

    这个作业属于那个课程 C语言程序设计II 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/CST2019-3/homework/9827 我在这个课程的目 ...

  9. 使用注解方式搭建SpringMVC

    1.以前搭建Spring MVC 框架一般都使用配置文件的方式进行,相对比较繁琐.spring 提供了使用注解方式搭建Spring MVC 框架的方式,方便简洁.使用Spring IOC 作为根容器管 ...

  10. idea常用快捷键列表

    在使用IntelliJ Idea的时候,使用快捷键是必不可少的.掌握一些常用的快捷键能大大提高我们的开发效率.有些快捷键可以熟练的使用,但是还有另外一些快捷键虽然很好用,但是由于因为没有形成使用习惯或 ...