• 自定义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. 漫谈 MyCat 配置系统

    上篇文章<MyCat 启蒙:分布式系统的数据库架构演变>中,我们通过一个项目从零到百万级访问的变化,展示了这个过程中的数据层架构变化.其中说到了数据层架构变化所带来的三个问题: 读写数据源 ...

  2. 【洛谷P4393】Sequence

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

  3. vue导航菜单动态展示

    地址:https://blog.csdn.net/qq_31126175/article/details/81875468      

  4. Python 日期和时间Ⅱ

    获取某月日历 Calendar模块有很广泛的方法用来处理年历和月历,例如打印某月的月历: 以上实例输出结果: Time 模块 Time 模块包含了以下内置函数,既有https://www.xuanhe ...

  5. 21.栈的压入、弹出序列(python)

    题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序.假设压入栈的所有数字均不相等.例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压 ...

  6. docker-compose命令及yaml文件

    Docker-compose常用命令 docker-compose up -d nginx 构建建启动nignx容器 docker-compose exec nginx bash 登录到nginx容器 ...

  7. 能给个安全点的fifo吗

      调试一个基于altera  FPGA的项目,发现开机200次,就会有1到2次的开机不正常现象,但只要是成功开机了,无论运行多久都是正常的.   遇到这类问题,按照经验来说 一般首先想到的可能是电源 ...

  8. Python爬虫十六式 - 第四式: 使用Xpath提取网页内容

    Xpath:简单易用的网页内容提取工具 学习一时爽,一直学习一直爽 !   Hello,大家好,我是Connor,一个从无到有的技术小白.上一次我们说到了 requests 的使用方法.到上节课为止, ...

  9. python 输出一个随机数

    题目:输出一个随机数. 程序分析:使用 random 模块. #!/user/bin/env python #coding:utf-8 import random print random.rando ...

  10. 在Linux下使用命令行打印文件

    近期需要将数学笔记打印出来复习,才发现Linux KDE环境下的默认PDF软件Okular根本无法将我在GoodNotes B5大小的页面写下的内容自适应地放大到A4纸上,只能以页面的原始尺寸打印.然 ...