Programme.cs
using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using System.Text; using WebApiYzk.Models; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); //这里给Swagger指定说要使用Authorization 在swagger页面会出现一个小锁按钮,输入 jwttoken就行了 builder.Services.AddSwaggerGen(c => { var scheme = new OpenApiSecurityScheme() { Description = "Authorization header. /r/nExample: 'Bearer 12345abcdef'", Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Authorization" }, Scheme = "oauth2", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }; c.AddSecurityDefinition("Authorization", scheme); var requirement = new OpenApiSecurityRequirement(); requirement[scheme] = new List<string>(); c.AddSecurityRequirement(requirement); }); //从配置文件中读取 JWT 节点,转换到 JwtOption对象上,在Login方法的 FromService 时用 builder.Services.Configure<JwtOption>(builder.Configuration.GetSection("JWT")); //注册JwtBear,设置一些验证的项 builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(x => { var jwtOpt = builder.Configuration.GetSection("JWT").Get<JwtOption>(); byte[] keyBytes = Encoding.UTF8.GetBytes(jwtOpt.SigningKey); var scrkey = new SymmetricSecurityKey(keyBytes); x.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = true, ValidateIssuerSigningKey = true, IssuerSigningKey = scrkey }; }); var app = builder.Build(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); //认证 需要加这个中间件 app.UseAuthentication(); //授权 app.UseAuthorization(); app.MapControllers(); app.Run();
View Code
写一个Login返回jwttoken
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using WebApiYzk.Models; namespace WebApiYzk.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class LoginController : ControllerBase { [HttpPost] public async Task<IActionResult> Login(LoginRequest rq,[FromServices]IOptionsSnapshot<JwtOption> jwtOptions) { if (rq.UserName != "admin") return NotFound("没有找到"); var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, rq.UserName)); claims.Add(new Claim(ClaimTypes.Role, "管理员")); string jwtToken = BuildToken(claims, jwtOptions.Value); return Ok(jwtToken); } private static string BuildToken(IEnumerable<Claim> claims, JwtOption options) { DateTime expires = DateTime.Now.AddSeconds(options.ExpireSeconds); byte[] keyBytes = Encoding.UTF8.GetBytes(options.SigningKey); var secKey = new SymmetricSecurityKey(keyBytes); var credentials = new SigningCredentials(secKey, SecurityAlgorithms.HmacSha256Signature); var tokenDescriptor = new JwtSecurityToken(expires: expires, signingCredentials: credentials, claims: claims); return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor); } } }
View Code
写一个方法,需要验证登录信息后才能访问:
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Security.Claims; namespace WebApiYzk.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class SayHiController : ControllerBase { [HttpGet] public IActionResult Hello() { string id = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value; string userName = this.User.FindFirst(ClaimTypes.NameIdentifier)!.Value; IEnumerable<Claim> roleClaims = this.User.FindAll(ClaimTypes.Role); string roleNames = string.Join(',', roleClaims.Select(c => c.Value)); return Ok($"id={id},userName={userName},roleNames ={roleNames}"); } } }
View Code
用到的类
public class JwtOption { public string SigningKey { get; set; } public int ExpireSeconds { get; set; } } public class Role : IdentityRole<long> { } public class User : IdentityUser<long> { public string UserName { get; set; } public DateTime CreatTime { get; set; } } public class LoginRequest { public string UserName { get; set; } public string Password { get; set; } }
View Code
这只是基础例子,可以看杨老师源码,多了一些内容
视频:
Part5-7:让Swagger中带JWT报文头_哔哩哔哩_bilibili
NETBookMaterials/第八章/ASPNETCore_JWT1 at main · yangzhongke/NETBookMaterials · GitHub
自己可见:第八章/ASPNETCore_JWT1 · 物华天宝/NETBookMaterials – 码云 – 开源中国 (gitee.com)
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/279791.html