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; } } }
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(); } } }