• 自定义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授权的更多相关文章

  1. .net core 学习小结之 JWT 认证授权

    新增配置文件 { "Logging": { "IncludeScopes": false, "Debug": { "LogLeve ...

  2. 如何使用Swagger为.NET Core 3.0应用添加JWT授权说明文档

    简介 本教程采用WHY-WHAT-HOW黄金圈思维模式编写,黄金圈法则强调的是从WHY为什么学,到WHAT学到什么,再到HOW如何学.从模糊到清晰的学习模式.大家的时间都很宝贵,我们做事前先想清楚为什 ...

  3. 学习ASP.NET Core(05)-使用Swagger与Jwt授权

    上一篇我们使用IOC容器解决了依赖问题,同时简单配置了WebApi环境,本章我们使用一下Swagger,并通过Jwt完成授权 一.Swagger的使用 1.什么是Swagger 前后端分离项目中,后端 ...

  4. .net core 学习小结之 PostMan报415

    首先415的官方解释是:对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝. 也就是说我所准备的数据格式并不是后台代码使用的数据格式 后台代码如下 using ...

  5. 【.Net Core 学习系列】-- 自定义错误页面在IE浏览器中不能正常显示

    测试场景: 1. 新建.Net Core Web项目 2. 选择模板: 3. 修改Error页面代码:(去掉母版页并修改页面显示信息) 4. 修改[ASPNETCORE_ENVIRONMENT],并抛 ...

  6. .net core 学习小结之 Cookie-based认证

    在startup中添加授权相关的管道 using System; using System.Collections.Generic; using System.Linq; using System.T ...

  7. .net core 学习小结之环境配置篇

    安装IIs对 netcore 的支持 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-mod ...

  8. .Net Core 学习依赖注入自定义Service

    1. 定义一个服务,包含一个方法 public class TextService { public string Print(string m) { return m; } } 2. 写一个扩展方法 ...

  9. .net core 学习小结之 配置介绍(config)以及热更新

    命令行的配置 var settings = new Dictionary<string, string>{ { "name","cyao"}, {& ...

随机推荐

  1. CentOS7安装并使用Ceph

    1.准备工作1.1 安装配置NTP官方建议在所有 Ceph 节点上安装 NTP 服务(特别是 Ceph Monitor 节点),以免因时钟漂移导致故障. ln -sf /usr/share/zonei ...

  2. 一张图明白jenkins和docker作用

    可以看出,jenkins充当的是一个自动构建的作用,构建完后自动部署到机器上.如果没有docker,那么就是直接把打包好的jar包直接部署到服务器.现在是把jar包部署到服务器上的docker容器上. ...

  3. 【洛谷P4393】Sequence

    题目大意:给定一个长度为 N 的序列,每次可以合并相邻的两个元素,代价是两者中较大的值,合并之后的值也为两者较大的值,求合并 N-1 次后的最小代价是多少. 题解: 除了最大值以外,每个值均只会被合并 ...

  4. 【HDU4034】Graph

    题目大意:给定一个图的最短路,求原图中至少存在多少条边. 题解:利用 Floyd 的性质,枚举边 d[i][j],若存在一个不是两端点的点,使得 d[i][j]=d[i][k]+d[k][j] 成立, ...

  5. Docker(3)--常用命令

    1.docker -h 帮助 2.获取镜像 docker pull NAME[:TAG] [root@node3 ~]#docker pull centos:latest 3.启动Container盒 ...

  6. pt-online-schema-change的用法

    pt-online-schema-change的用法 环境: 10.192.30.53 主库 10.192.30.60 从库 mysql版本:8.0.17 为了方便操作,简单的写了如下的脚本. #!/ ...

  7. mysql57 在windows 下无法修改 大小写设置

    参考: https://blog.csdn.net/ceciliawanghenan/article/details/82916662 清空data文件,我的data文件在programdata\My ...

  8. 19. ClustrixDB 执行计划解读

    EXPLAIN语句用于显示ClustrixDB查询优化器(也称为Sierra)如何执行INSERT.SELECT.UPDATE和DELETE语句.EXPLAIN的输出有三列: Operation - ...

  9. 编译caffe-gpu-cuda及cudnn-tar 下载地址

    y下载 https://github.com/BVLC/caffe https://github.com/BVLC/caffe/archive/master.zip gcc caffe安装 有2个问题 ...

  10. SpringApplication.run 做了哪些事?

    SpringApplication.run一共做了两件事,分别是 创建SpringApplication对象 利用创建好的SpringApplication对象,调用run方法论 结论: 面试官: 我 ...