[Authorize] ==== using Microsoft.AspNetCore.Authorization;
登录的 DTO
namespace login; public class WeatherForecast { public DateOnly Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string? Summary { get; set; } }
program.cs 实现 jwt 注册
using Microsoft.IdentityModel.Tokens; using System.Text; using Microsoft.AspNetCore.Authentication.JwtBearer; 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(); builder.Services.AddSwaggerGen(); builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { //取出私钥 var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]); options.TokenValidationParameters = new TokenValidationParameters() { //验证发布者 ValidateIssuer = true, ValidIssuer = builder.Configuration["Authentication:Issuer"], //验证接收者 ValidateAudience = true, ValidAudience = builder.Configuration["Authentication:Audience"], //验证是否过期 ValidateLifetime = true, //验证私钥 IssuerSigningKey = new SymmetricSecurityKey(secretByte) }; }); var app = builder.Build(); //添加jwt验证 app.UseAuthentication(); app.UseAuthorization(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
csproj 依赖管理
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net7.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.17-preview.2.24128.4" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" /> </ItemGroup> </Project>
appsetting.json
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "Authentication": { "SecretKey": "nadjhfgkadshgoihfkajhkjdhsfaidkuahfhdksjaghidshyaukfhdjks", "Issuer": "www.adsfsadfasdf", "Audience": "www.adsfsadfasdf" } }
Controller 控制器:
using Microsoft.AspNetCore.Mvc; using login.Dtos; using Microsoft.IdentityModel.Tokens; using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using System.IdentityModel.Tokens.Jwt; using System.Text; namespace login.Controllers; [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; public readonly IConfiguration _configuration; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration) { _logger = logger; _configuration = configuration; } [HttpPost("testLogin")] public IActionResult Login([FromBody] LoginDto loginDto) { //1.验证用户账号密码是否正确,暂时忽略,因为我们是模拟登录 //2.生成JWT //Header,选择签名算法 var signingAlogorithm = SecurityAlgorithms.HmacSha256; System.Console.WriteLine("算法"); System.Console.WriteLine(signingAlogorithm); var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub,"user_id"), new Claim(ClaimTypes.Role,"admin") }; //取出私钥并以utf8编码字节输出 var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]); //使用非对称算法对私钥进行加密 var signingKey = new SymmetricSecurityKey(secretByte); //使用HmacSha256来验证加密后的私钥生成数字签名 var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm); //生成Token var Token = new JwtSecurityToken( issuer: _configuration["Authentication:Issuer"], //发布者 audience: _configuration["Authentication:Audience"], //接收者 claims: claims, //存放的用户信息 notBefore: DateTime.UtcNow, //发布时间 expires: DateTime.UtcNow.AddDays(1), //有效期设置为1天 signingCredentials //数字签名 ); //生成字符串 token var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token); return Ok(TokenStr); } /// <summary> /// [Authorize(Roles = "admin")] 需要验证token 只允许 admin 角色使用 /// </summary> /// <returns></returns> [HttpGet(Name = "GetWeatherForecast")] [Authorize(Roles = "admin")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } }
实现基于jwt登录
标签:builder,实现,app,jwt,接口,new,var,using,public From: https://www.cnblogs.com/zhulongxu/p/18112653