- 自定义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的访问)
转载于:https://www.cnblogs.com/chongyao/p/8652885.html