- 新增配置文件
{ "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } }, "JwtSettings": { "Issuer": "http://locahost:5000", "Audience": "http://locahost:5000", "SecretKey": "hello world this is my key for cyao" } }
namespace JwtAuth { public class JwtSettings { ///使用者 public string Issuer { get; set; } ///颁发者 public string Audience { get; set; } ///秘钥必须大于16个字符 public string SecretKey { get; set; } } }
- 将配置文件读取映射到实体类,并且将jwt授权加入到管道中
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)) }); 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(); } } }
- 判断当前用户是否合法并且返回授权后的token信息
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace JwtAuth.Controllers { using System.Security.Claims; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Microsoft.AspNetCore.Authentication.JwtBearer; //添加dll的引用 Nuget Microsoft.AspNetCore.Authentication.JwtBearer; using System.IdentityModel.Tokens.Jwt; [Route("Auth/[controller]")] public class AuthController : Controller { public JwtSettings settings; public AuthController(IOptions<JwtSettings> jwtsettings) { settings = jwtsettings.Value; } public IActionResult Token([FromBody]LoginInfo model) { if (ModelState.IsValid) { if (model.username == "cyao" && model.password == "123456") { //用户合法情况 //添加授权信息 var claims = new Claim[] { new Claim(ClaimTypes.Name, "cyao"), new Claim(ClaimTypes.Role, "admin") }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey)); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( settings.Issuer, settings.Audience, claims, DateTime.Now, DateTime.Now.AddMinutes(30),//过期时间 creds); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } } return BadRequest(); } } public class LoginInfo { [Required] public string username { get; set; } [Required] public string password { get; set; } } }