Asp.Net Core 使用JWT,Swagger中带报文头
2022/8/11 1:22:59
本文主要是介绍Asp.Net Core 使用JWT,Swagger中带报文头,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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)
这篇关于Asp.Net Core 使用JWT,Swagger中带报文头的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-12-06使用Microsoft.Extensions.AI在.NET中生成嵌入向量
- 2024-11-18微软研究:RAG系统的四个层次提升理解与回答能力
- 2024-11-15C#中怎么从PEM格式的证书中提取公钥?-icode9专业技术文章分享
- 2024-11-14云架构设计——如何用diagrams.net绘制专业的AWS架构图?
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#