【ASP.NET Core快速入门】(十二)JWT 设计解析及定制

前言

上一节我们讲述的书如何使用jwt token,而且上一节的token是要加Authorization:bearer XXXXXXXXXXXX才能访问。

这一节我们来研究如何自定义类似jwt的token验证,也就是说直接从header中拿取我们想要的token

自己定制JWT

首先,继续在上一节的JwtAuthSample项目中的Startup.cs中的ConfigureServices方法中注释掉以下内容,然后自定义jwt token

        public void ConfigureServices(IServiceCollection services)
        {
            //将appsettings.json中的JwtSettings部分文件读取到JwtSettings中,这是给其他地方用的
            services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));

            //由于初始化的时候我们就需要用,所以使用Bind的方式读取配置
            //将配置绑定到JwtSettings实例中
            var jwtSettings=new JwtSettings();
            Configuration.Bind("JwtSettings",jwtSettings);

            services.AddAuthentication(options=>{
                //认证middleware配置
                options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o=>{
                // //主要是jwt  token参数设置
                // o.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
                //     ValidIssuer =jwtSettings.Issuer,
                //     ValidAudience =jwtSettings.Audience,
                //     //这里的key要进行加密,需要引用Microsoft.IdentityModel.Tokens
                //     IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey))
                // };

                o.SecurityTokenValidators.Clear();//将SecurityTokenValidators清除掉,否则它会在里面拿验证

                o.Events=new JwtBearerEvents{
                    //重写OnMessageReceived
                    OnMessageReceived=context=>{
                        var token=context.Request.Headers["mytoken"];
                        context.Token=token.FirstOrDefault();
                        return Task.CompletedTask;
                    }
                };
            });

            services.AddMvc();
        }

接下来我们新建MyTokenValidator.cs类来验证token,并让这个类实现ISecurityTokenValidator接口

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;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;

namespace JwtAuthSample
{
    public class MyTokenValidator : ISecurityTokenValidator
    {
        bool ISecurityTokenValidator.CanValidateToken =>true;

        int ISecurityTokenValidator.MaximumTokenSizeInBytes { get; set; }

        bool ISecurityTokenValidator.CanReadToken(string securityToken)
        {
            return true;
        }

        //验证token
        ClaimsPrincipal ISecurityTokenValidator.ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            validatedToken=null;
            //判断token是否正确
            if(securityToken!="abcdefg")
            return null;

            //给Identity赋值
            var identity=new ClaimsIdentity(JwtBearerDefaults.AuthenticationScheme);
            identity.AddClaim(new Claim("name","wyt"));
            identity.AddClaim(new Claim(ClaimsIdentity.DefaultRoleClaimType,"admin"));

            var principle=new ClaimsPrincipal(identity);
            return principle;
        }
    }

}

然后我们在Startup.cs的ConfigureServices方法中将我们自定义的MyTokenValidator验证加进去

o.SecurityTokenValidators.Add(new MyTokenValidator());

这时候我们执行dotnet watch run运行项目,用postman不加header头或加错误的hearder头,发现无法访问

我们用正确的自定义token进行访问

Role以及Claims授权

Role授权

我们之前的授权方式都是添加  [Authorize]  标签但是由于我们在Claim中设置了Role

所以我们可以将  [Authorize]  标签写成[Authorize(Roles="admin")]

只有解析出来的token中的角色为admin才授权成功

Claims授权

要使用Claims授权,我们首先需要在Startup.cs的ConfigureServices方法中添加授权

            //添加Claim授权
            services.AddAuthorization(options=>{
                options.AddPolicy("SuperAdminOnly",policy=>{policy.RequireClaim("SuperAdminOnly");});
            });

然后在AuthorizeController.cs生成token的action中的Claim中添加SuperAdminOnly

最后在需要权限认证的地方使用标签    [Authorize(Policy="SuperAdminOnly")]

我们首先获取一下token,到jwt官网上解析一下发现token中包含SuperAdminOnly

然后访问成功

原文地址:https://www.cnblogs.com/wyt007/p/8196747.html

时间: 2024-08-21 16:31:43

【ASP.NET Core快速入门】(十二)JWT 设计解析及定制的相关文章

【ASP.NET Core快速入门】(二)部署到IIS

原文:[ASP.NET Core快速入门](二)部署到IIS 配置IIS模块 ASP.NET Core Module载地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-module?tabs=aspnetcore2x 安装后再IIS管理器模块页面会出现aspnetcoremodule 新建网站 修改应用池 网站发布 控制台方式 dotnet publish发布到项目文件的bin/deb

ASP.NET Core 2.1 : 十二.内置日志、使用Nlog将日志输出到文件

应用离不开日志,虽然现在使用VS有强大的调试功能,开发过程中不复杂的情况懒得输出日志了(想起print和echo的有木有),但在一些复杂的过程中以及应用日常运行中的日志还是非常有用. ASP.NET Core提供了内置的日志,但没弄明白这么把它输出到文件, 只能在VS的输出中查看, 谁知道怎么弄告诉我一下.(ASP.NET Core 系列目录) 本例 GitHub 一.内置日志的使用 上一篇:如何在后台运行一个任务  中使用到了内置的日志,直接在构造中注入一下,然后直接使用即可, 非常方便 pu

【ASP.NET Core快速入门】(一)环境安装

下载.NET Core SDK 下载地址:https://www.microsoft.com/net/download/windows https://www.microsoft.com/net/learn/get-started/windows 安装vs2017,安装的时候选择安装core跨平台 在控制台创建ASP.NET Core应用程序 在程序安装后,可以在控制台输入dotnet进行创建core应用程序 输入dotnet  --help查看命令帮助 .NET 命令行工具 (2.1.2) 使

ASP.NET Core快速入门(Jessetalk)(第2章:配置管理)

课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务9:配置介绍 命令行配置 Json文件配置 从配置文件文本到c#对象实例的映射 - Options 与 Bind 配置文件热更新 框架设计:Configuration 任务10:命令行配置 新建一个项目CommandLineSample--控制台应用(.NET Core) 依赖性右键--管理NuGet程序包--下载microsoft.aspnetcore.all 传入参数

ASP.NET Core快速入门(Jessetalk)(第三章:依赖注入)

课程链接:http://video.jessetalk.cn/course/explore 良心课程,大家一起来学习哈! 任务16:介绍 1.依赖注入概念详解 从UML和软件建模来理解 从单元测试来理解 2.ASP.NET Core 源码解析 任务17:从UML角度来理解依赖 1.什么是依赖 当一个类A完成某个任务需要另一个类B来帮助时,A就对B产生了依赖 例如CustomerController需要对customer进行新增或查找时用到EF,则对EF的Context产生了依赖 var cont

【ASP.NET Core快速入门】(十四)MVC开发:UI、 EF + Identity实现

前言 之前我们进行了MVC的web页面的Cookie-based认证实现,接下来的开发我们要基于之前的MvcCookieAuthSample项目做修改. MvcCookieAuthSample项目地址:http://www.cnblogs.com/wyt007/p/8128186.html UI 我们首先在AccountController中添加两个Action public IActionResult SignIn() { return View(); } public IActionResu

【ASP.NET Core快速入门】(三)准备CentOS和Nginx环境

基本软件 VMware虚拟机 centos:http://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-Minimal-1708.iso centos安装 打开VMware虚拟机,选择文件----新建虚拟机 一般下载好的CentOS系统放在VMware文件夹下 选择网络方式(一般NAT就够了) 后面的都选择默认的就行了 然后运行就可以了 语言选英文 选择位置 然后开始安装 输入密码root123 然后等待安装完成就可以了,

Asp.Net Core 快速入门-在Centos 上安装Nginx

第一步:添加CentOS 7EPEL 库 在终端运行一下命令 sudo yum install epel-release 第二步:安装Nginx 在终端运行命一下 sudo yum install nginx 你回答“yes”的提示后,nginx会完成安装到你的虚拟专用服务器(VPS) 第三步:启动Nginx sudo systemctl start nginx 启动完成之后我们就可以用CentOS的IP和80端口访问Nginx了 如果无法访问,说明还是有问题 If you are runnin

Asp.Net Core WebAPI入门整理(二)简单示例

一.Core WebAPI中的序列化 使用的是Newtonsoft.Json,自定义全局配置处理: // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //使用IMvcBuilder 配置Json序列化处理 services.AddMvc()