一、Startup类配置
ConfigureServices中
//添加jwt验证: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//是否验证Issuer ValidateAudience = true,//是否验证Audience ValidateLifetime = true,//是否验证失效时间 ValidateIssuerSigningKey = true,//是否验证SecurityKey ValidIssuer = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Issuer ValidAudience = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Audience IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) };//appsettings.json文件中定义的JWT Key });
Configure 启用中间件
app.UseAuthentication(); // 注意添加这一句,启用jwt验证
整体代码:
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) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //添加jwt验证: services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true,//validate the server ValidateAudience = true,//ensure that the recipient of the token is authorized to receive it ValidateLifetime = true,//check that the token is not expired and that the signing key of the issuer is valid ValidateIssuerSigningKey = true,//verify that the key used to sign the incoming token is part of a list of trusted keys ValidIssuer = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Issuer ValidAudience = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Audience IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])) };//appsettings.json文件中定义的JWT Key }); } // 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(); } //跨域 app.UseCors(builder => { builder.SetIsOriginAllowed(origin => true) .AllowAnyHeader() .WithMethods("GET", "POST") .AllowCredentials(); }); app.UseAuthentication(); // 注意添加这一句,启用jwt验证 app.UseMvc(); } }
二、appsetting.json中配置
"Jwt": { "Key": "veryVerySecretKey", "Issuer": "http://localhost:53111" }
整体代码:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "Jwt": { "Key": "veryVerySecretKey", "Issuer": "http://localhost:53111" }, "AllowedHosts": "*" }
如图:
三、Api控制器中 根据登录信息生成token令牌
整体代码:
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; namespace Temp.Controllers { [Route("api/[controller]/[action]")] //Api控制器 [ApiController] public class OAuthController : ControllerBase { private readonly IConfiguration _config; public OAuthController(IConfiguration configuration) { _config = configuration; } /// <summary> /// login /// </summary> /// <returns></returns> [HttpPost] public string Token(string user, string password) { //验证用户名和密码 var claims = new Claim[] { new Claim(ClaimTypes.Name, "John"), new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com") }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( //颁发者 issuer: _config["Jwt:Issuer"], //接收者 audience: _config["Jwt:Issuer"], //添加claims claims: claims, //指定token的生命周期,过期时间 expires: DateTime.Now.AddMinutes(30), //签名证书 signingCredentials: creds); //一个典型的JWT 字符串由三部分组成: //header: 头部,meta信息和算法说明 //payload: 负荷(Claims), 可在其中放入自定义内容, 比如, 用户身份等 //signature: 签名, 数字签名, 用来保证前两者的有效性 //三者之间由.分隔, 由Base64编码.根据Bearer 认证规则, 添加在每一次http请求头的Authorization字段中, 这也是为什么每次这个字段都必须以Bearer jwy - token这样的格式的原因. return new JwtSecurityTokenHandler().WriteToken(token); } } }
四、对授权的进行验证
效果如下:
获取资源:
注意:这个地方要默认取消