.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的访问)
stay hungry stay foolish!
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 内存占用高分析
· .NET Core GC计划阶段(plan_phase)底层原理浅谈
· .NET开发智能桌面机器人:用.NET IoT库编写驱动控制两个屏幕
· 用纯.NET开发并制作一个智能桌面机器人:从.NET IoT入门开始
· 一个超经典 WinForm,WPF 卡死问题的终极反思
· 20250116 支付宝出现重大事故 有感
· 一个基于 Roslyn 和 AvalonEdit 的跨平台 C# 编辑器
· 2025 最佳免费商用文本转语音模型: Kokoro TTS
· 海康工业相机的应用部署不是简简单单!?
· 在 .NET Core中如何使用 Redis 创建分布式锁