.net core 学习小结之 Cookie-based认证
- 在startup中添加授权相关的管道
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; namespace mvcforcookie
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option => option.LoginPath = "/Acounnt/Index");
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
} - 将需要权限访问的页面贴上特性标签
[Authorize(Roles="Admin")] 表名只有Admin身份的人才能进入Admin控制器
- 用户成功输入用户名和密码之后生成用户票据
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using mvcforcookie.Models; namespace mvcforcookie.Controllers
{
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
public class AcounntController : Controller
{
public IActionResult Index()
{
//数据库查询用户输入的用户名和密码等一系列匹配操作
//模拟用户登录后的操作
//创建一个用户身份
var claims=new List<Claim>{
new Claim(ClaimTypes.Name,"cyao"),
new Claim(ClaimTypes.Role,"Admin")
};
var claimidentity=new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
//向上下文容器中添加当前用户
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimidentity));
return Ok();
}
public IActionResult LoginOut()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
} - 如果要获取当前用户的身份和用户名的话
ViewBag.User= User.Claims.Where(c =>c.Type==ClaimTypes.Name).First().Value;
ViewBag.Type= User.Claims.Where(c =>c.Type==ClaimTypes.Role).First().Value;
.net core 学习小结之 Cookie-based认证的更多相关文章
- .net core 学习小结之 JWT 认证授权
新增配置文件 { "Logging": { "IncludeScopes": false, "Debug": { "LogLeve ...
- .net core 学习小结之环境配置篇
安装IIs对 netcore 的支持 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-mod ...
- .net core 学习小结之 自定义JWT授权
自定义token的验证类 using System; using System.Collections.Generic; using System.IO; using System.Linq; usi ...
- .net core 学习小结之 PostMan报415
首先415的官方解释是:对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝. 也就是说我所准备的数据格式并不是后台代码使用的数据格式 后台代码如下 using ...
- .net core 学习小结之 配置介绍(config)以及热更新
命令行的配置 var settings = new Dictionary<string, string>{ { "name","cyao"}, {& ...
- ASP.NET CORE中使用Cookie身份认证
大家在使用ASP.NET的时候一定都用过FormsAuthentication做登录用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cook ...
- NET Core 2.0使用Cookie认证实现SSO单点登录
NET Core 2.0使用Cookie认证实现SSO单点登录 之前写了一个使用ASP.NET MVC实现SSO登录的Demo,https://github.com/bidianqing/SSO.Sa ...
- Asp.net core 学习笔记 ( identity server 4 JWT Part )
更新 : id4 使用这个 DbContext 哦 dotnet ef migrations add identity-server-init --context PersistedGrantDbCo ...
- .NET Core 学习资料精选:入门
开源跨平台的.NET Core,还没上车的赶紧的,来不及解释了-- 本系列文章,主要分享一些.NET Core比较优秀的社区资料和微软官方资料.我进行了知识点归类,让大家可以更清晰的学习.NET Co ...
随机推荐
- Python核心技术与实战——十六|Python协程
我们在上一章将生成器的时候最后写了,在Python2中生成器还扮演了一个重要的角色——实现Python的协程.那什么是协程呢? 协程 协程是实现并发编程的一种方式.提到并发,肯很多人都会想到多线程/多 ...
- calculate_gain
torch.nn.init.calculate_gain(nonlinearity,param=None) 对于给定的非线性函数,返回推荐的增益值.这些值如下所示: relu_gain=nn.init ...
- Iconfont 阿里图库使用(小程序和H5)
前言 现在前端发展的太快,前端优化也是,图片也是被近2年来比较火的就是阿里图库取代了,不管小程序还是H5 都在用 好了,那么就介绍下如何使用吧 阿里图库 当然需要你到阿里官网 http://www.i ...
- python基础31[常用模块介绍]
python基础31[常用模块介绍] python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的li ...
- get和post请求的区别?
①get请求用来从服务器上获得资源,而post是用来向服务器提交数据: ②get将表单中数据按照name=value的形式,添加到action 所指向的URL 后面,并且两者使用“?”连接,而各个变量 ...
- python 面向对象_2
self的理解 通俗理解self就是实例对象,实例化的是什么,self就是什么 实例变量: 经过实例化才能使用的变量 class Person(): def __init__(self,id,name ...
- CSS水印“点击穿透”
- Codeforces 988D Points and Powers of Two ( 思维 || 二的幂特点 )
题目链接 题意 : 给出坐标轴上的 n 个点的横坐标,要你选出最多的点,使得这些点两两距离是二的幂 ( 特殊情况 : 选出的集合只有一个点也满足条件 ) 分析 : 官方题解已经说的很好了 最关键是是判 ...
- sh_06_函数的返回值
sh_06_函数的返回值 def sum_2_num(num1, num2): """对两个数字的求和""" result = num1 + ...
- sh_02_快速体验
sh_02_快速体验 import sh_01_九九乘法表 sh_01_九九乘法表.multiple_table()