.net core 学习小结之 自定义JWT授权
- 自定义token的验证类
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; namespace JwtAuth
{
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
public class MyTokenValidata : ISecurityTokenValidator
{
//判断当前token是否有值
public bool CanValidateToken => true; public int MaximumTokenSizeInBytes { get; set; }//顾名思义是验证token的最大bytes public bool CanReadToken(string securityToken)
{
return true;
}
///验证securityToken
public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
{
validatedToken = null;
if (securityToken != "yourtoken")
{
return null;
}
var identity = new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
identity.AddClaim(new Claim("name", "cyao"));
identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType, "admin"));
identity.AddClaim(new Claim("SuperAdmin", "true"));//添加用户访问权限
var principal = new ClaimsPrincipal(identity);
return principal;
}
}
} - 在strtup注册自定义验证的管道代码
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;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace JwtAuth
{
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
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)
{
//将配置文件读取到settings
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
JwtSettings settings = new JwtSettings();
Configuration.Bind("JwtSettings", settings);
//添加授权信息
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
.AddJwtBearer(c =>
// c.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters//添加jwt 授权信息
// {
// ValidIssuer = settings.Issuer,
// ValidAudience = settings.Audience,
// IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey))
// }
// ------------------------自定义分割线-------------------------
{
c.SecurityTokenValidators.Clear();//清除默认的设置
c.SecurityTokenValidators.Add(new MyTokenValidata());//添加自己设定规则的验证方法
c.Events = new JwtBearerEvents()
{
OnMessageReceived = context =>
{
var token = context.Request.Headers["mytokens"];//修改默认的http headers
context.Token = token.FirstOrDefault();
return Task.CompletedTask;
}
};
}
);
//只允许superadmin进行访问claims
services.AddAuthorization(options => options.AddPolicy("SuperAdmin", policy => policy.RequireClaim("SuperAdmin")));
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();
}
//向builder中添加授权的管道
app.UseAuthentication();
app.UseMvc();
}
}
} - 最终在api的最上方贴上对应的特性标签(这种是基于claims的访问)
.net core 学习小结之 自定义JWT授权的更多相关文章
- .net core 学习小结之 JWT 认证授权
新增配置文件 { "Logging": { "IncludeScopes": false, "Debug": { "LogLeve ...
- 如何使用Swagger为.NET Core 3.0应用添加JWT授权说明文档
简介 本教程采用WHY-WHAT-HOW黄金圈思维模式编写,黄金圈法则强调的是从WHY为什么学,到WHAT学到什么,再到HOW如何学.从模糊到清晰的学习模式.大家的时间都很宝贵,我们做事前先想清楚为什 ...
- 学习ASP.NET Core(05)-使用Swagger与Jwt授权
上一篇我们使用IOC容器解决了依赖问题,同时简单配置了WebApi环境,本章我们使用一下Swagger,并通过Jwt完成授权 一.Swagger的使用 1.什么是Swagger 前后端分离项目中,后端 ...
- .net core 学习小结之 PostMan报415
首先415的官方解释是:对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝. 也就是说我所准备的数据格式并不是后台代码使用的数据格式 后台代码如下 using ...
- 【.Net Core 学习系列】-- 自定义错误页面在IE浏览器中不能正常显示
测试场景: 1. 新建.Net Core Web项目 2. 选择模板: 3. 修改Error页面代码:(去掉母版页并修改页面显示信息) 4. 修改[ASPNETCORE_ENVIRONMENT],并抛 ...
- .net core 学习小结之 Cookie-based认证
在startup中添加授权相关的管道 using System; using System.Collections.Generic; using System.Linq; using System.T ...
- .net core 学习小结之环境配置篇
安装IIs对 netcore 的支持 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-mod ...
- .Net Core 学习依赖注入自定义Service
1. 定义一个服务,包含一个方法 public class TextService { public string Print(string m) { return m; } } 2. 写一个扩展方法 ...
- .net core 学习小结之 配置介绍(config)以及热更新
命令行的配置 var settings = new Dictionary<string, string>{ { "name","cyao"}, {& ...
随机推荐
- windows中ftp下载脚本(bat+vb)
做了个ftp下载脚本: ftpdownload.bat @rem 注释:从ftp服务器每小时下载北向性能文件的脚本 @rem 用vb脚本取昨天 for /f %%a in ('cscript //no ...
- QT程序在发布的时候应注意的地方
---恢复内容开始--- 我们用QT开发好的应用程序,如果要发布到其他计算机上运行怎么办呢?我们在用VC编程时,单独运行编译好的可执行文件时,经常会发现提示缺少动态库.用QT编程也不例外,在一定程度上 ...
- 图片转base64的几种场景(网络图片,本地图片,用户上传图片)
转载于博客园 https://www.cnblogs.com/zhangdiIT/p/7895903.html 写的很棒 推荐给大家 场景一:将用户本地上传的资源转化,即用户通过浏览器点击文件上传时 ...
- day_14 匿名函数与内置函数连用 作业题
''' 要求: 从文件中取出每一条记录放入列表中,列表的每个元素都是` {'name':'egon','sex':'male','age':18,'salary':3000}`的形式 ''' all_ ...
- 便捷删除QQ空间说说
用Chrome打开QQ空间说说(心情),按F12,在Console里面粘贴以下代码,按回车 var delay = 1000; function del() { document.querySelec ...
- 对js库的调研研究------引用
1. 引言 从以下几个方面来阐述这个问题: 特性. 稳定性. 性能. 包生态. 社区. 学习曲线. 文档. 工具. 发展历史. 团队. 兼容性. 趋势. 2.概述 & 精读 特性 当你调研一个 ...
- fabric报错:Fatal error: run() received nonzero return code 1 while executing!
今天在使用fabric远程安装rpm时,一直报:Fatal error: run() received nonzero return code 1 while executing! 这看起来也是没笔病 ...
- jsonp跨域实例
一.什么是跨域 二.如何解决跨域 1.前端常用 JSONP 2.服务器端配置 HTTP 协议的 header 解析 三.JSONP实现的实例 <!DOCTYPE html> <htm ...
- java8中接口default、static新特性,与抽象类区别
之前Java接口中的方法默认都是public abstract,成员变量默认都是public static final,偶然发现接口中可以有default类型的方法,才知道java8中接口可以有自己的 ...
- 论文阅读:FlexGate: High-performance Heterogeneous Gateway in Data Centers
摘要: 大型数据中心通过边界上的网关对每个传入的数据包执行一系列的网络功能,例如,ACL被部署来阻止不合格的流量,而速率限制被用于防止供应商过度使用带宽,但是由于流量的规模巨大,给网关的设计和部署带来 ...
