Asp .Net Core 2.0 登录授权以及多用户登录
用户登录是一个非常常见的应用场景 .net core 2.0 的登录方式发生了点变化,应该是属于是良性的变化,变得更方便,更容易扩展。
配置
打开项目中的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 ?? "~/");
}
原文地址:http://www.zkea.net/codesnippet/detail/post-60
Asp .Net Core 2.0 登录授权以及多用户登录的更多相关文章
- Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- asp.net core 2.0 web api基于JWT自定义策略授权
JWT(json web token)是一种基于json的身份验证机制,流程如下: 通过登录,来获取Token,再在之后每次请求的Header中追加Authorization为Token的凭据,服务端 ...
- ASP.NET Core 3.0 一个 jwt 的轻量角色/用户、单个API控制的授权认证库
目录 说明 一.定义角色.API.用户 二.添加自定义事件 三.注入授权服务和中间件 三.如何设置API的授权 四.添加登录颁发 Token 五.部分说明 六.验证 说明 ASP.NET Core 3 ...
- ASP.NET Core 6.0 添加 JWT 认证和授权
序言 本文将分别介绍 Authentication(认证) 和 Authorization(授权). 并以简单的例子在 ASP.NET Core 6.0 的 WebAPI 中分别实现这两个功能. 相关 ...
- ASP.NET Core 3.0 gRPC 身份认证和授权
一.开头聊骚 本文算是对于 ASP.NET Core 3.0 gRPC 研究性学习的最后一篇了,以后在实际使用中,可能会发一些经验之文.本文主要讲 ASP.NET Core 本身的认证授权和gRPC接 ...
- asp.net Core 2.0 MVC为Controller或Action添加定制特性实现登录验证
前言:最近在倒腾 微软的新平台 asp.net Core 2.0,在这个过程中有些东西还是存在差异.下面是我在学习过程的一点笔记.有不妥之处,望各位大虾指正! 一.先创建一个控制器继承于Control ...
- 在 Mac OS 上创建并运行 ASP.NET Core 1.0 网站
var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...
- ASP.NET Core 1.0 入门——Application Startup
var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...
- 从头编写 asp.net core 2.0 web api 基础框架 (1)
工具: 1.Visual Studio 2017 V15.3.5+ 2.Postman (Chrome的App) 3.Chrome (最好是) 关于.net core或者.net core 2.0的相 ...
随机推荐
- python基础(四)集合
[集合特点] 1.天生去重.循环 2 关系测试 -交集,差集,并集,(反向差集,对称差集) list = [1,2,3,4,5,3,6]list_2 =[2,3,5,7,8]list=set(lis ...
- L1-049. 天梯赛座位分配
天梯赛每年有大量参赛队员,要保证同一所学校的所有队员都不能相邻,分配座位就成为一件比较麻烦的事情.为此我们制定如下策略:假设某赛场有 N 所学校参赛,第 i 所学校有 M[i] 支队伍,每队 10 位 ...
- Python socket文件传送md5校验
soket_server import socket,os,hashlib server = socket.socket() server.bind(('0.0.0.0',9999)) server. ...
- CentOS 6.5优化开机启动服务
使用chkconfig命令列举出所有服务,配合管道筛选出开机默认启动的服务,再去掉level0(关机).level4(无意义)和level6(重启)的显示,使结果更直观. chkconfig | gr ...
- ORA-600 [kcblin_3] 解决方法
今日,我们一个sql在某环境执行出错,如下: ORA-00600: 内部错误代码, 参数: [kcblin_3], [103], [253952], [8192], [32769], [312], [ ...
- activiti5/6 系列之--BpmnModel使用
BpmnModel对象,是activiti动态部署中很重要的一个对象,如果BpmnModel对象不能深入的理解,那可能如果自己需要开发一套流程设计器,使用bpmn-js使用前端或者C/S展现流程流转而 ...
- D1图论最短路专题
第一题:poj3660 其实是Floyed算法的拓展:Floyd-Wareshall.初始时,若两头牛关系确定则fij = 1. 对于一头牛若确定的关系=n-1,这说明这头牛的排名是确定的. 通过寻找 ...
- 剑指offer(59)按之字形顺序打印二叉树
题目描述 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 题目分析 这道题还是需要画图分析,不然不好找 ...
- laravel框架——Excel导入导出
一.composer安装PHPExcel插件 1.在框架根目录下安装依赖 composer require "maatwebsite/excel:~2.1.0" 2.打开框架在co ...
- ssm 整合(方案二 maven)
通过maven来整合ssm方便很多,至少不用去找jar包 具体架构如下: 1.配置pom.xml <project xmlns="http://maven.apache.org/POM ...