经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » ASP.net » 查看文章
如何在.net6webapi中配置Jwt实现鉴权验证
来源:cnblogs  作者:上帝视角丶观众老爷  时间:2023/6/2 11:03:31  对本文有异议

JWT(Json Web Token)

jwt是一种用于身份验证的开放标准,他可以在网络之间传递信息,jwt由三部分组成:头部,载荷,签名。头部包含了令牌的类型和加密算法,载荷包含了用户的信息,签名则是对头部和载荷的加密结果。

jwt鉴权验证是指在用户登录成功后,服务器生成一个jwt令牌并返回给客户端,客户端在后续的请求中携带该令牌,服务通过令牌的签名来确定用户的身份和权限。这种方式可以避免在每个请求中都需要进行身份验证,提高了系统的性能和安全性。

jwt具有以下优点:

1.无状态:jwt令牌包含了所有必要的信息,服务器不需要再每个请求中都进行身份验证,避免了服务器存储会话信息的开销。

2.可扩展性:jwt令牌可以包含任意的信息,可以根据需要添加自定义的字段。

3.安全性:jwt令牌使用签名来保证数据的完整性和真实性,防止数据被篡改或伪造。

4.跨平台:jwt令牌是基于json格式的,可以再不同的变成语言和平台之间进行传递和解析。

如何在webapi中使用JWT?

1.首先在项目中添加如下两个包

  1. dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
  1. dotnet add package System.IdentityModel.Tokens.Jwt

也可以直接在Nuget包管理工具中搜索

2.创建JwtOptions模型类,同时在appsetting.json中添加对应配置

  1. public class JwtOptions
  2. {
  3. /// <summary>
  4. /// 签发者
  5. /// </summary>
  6. public string Issuer { get; set; }
  7. /// <summary>
  8. /// 接收者
  9. /// </summary>
  10. public string Audience { get; set; }
  11. /// <summary>
  12. /// 密钥
  13. /// </summary>
  14. public string Key { get; set; }
  15. /// <summary>
  16. /// 过期时间
  17. /// </summary>
  18. public int ExpireSeconds { get; set; }
  19. }
  1. "JWT": {
  2. "Issuer": "签发方",
  3. "Audience": "接受方",
  4. "Key": "A86DA130-1B95-4748-B3B2-1B6AA9F2F743",//加密密钥
  5. "ExpireSeconds": 600 //密钥过期时间
  6. }

3.创建JWTExtensions静态类,添加AddJWTAuthentication扩展方法

  1. public static class JWTExtensions
  2. {
  3. public static AuthenticationBuilder AddJWTAuthentication(this IServiceCollection services, JwtOptions jwtOptions)
  4. {
  5. return services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  6. .AddJwtBearer(x =>
  7. {
  8. x.TokenValidationParameters = new()
  9. {
  10. ValidateIssuer = true,//是否验证发行商
  11. ValidateAudience = true,//是否验证受众者
  12. ValidateLifetime = true,//是否验证失效时间
  13. ValidateIssuerSigningKey = true,//是否验证签名键
  14. ValidIssuer = jwtOptions.Issuer,
  15. ValidAudience = jwtOptions.Audience,
  16. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOptions.Key))
  17. };
  18. });
  19. }
  20. }

4.创建SwaggerGenOptionsExtensions静态类,添加AddAuthenticationHeader扩展方法,为swagger增加Authentication报文头

 

  1. public static class SwaggerGenOptionsExtensions
  2. {
  3. /// <summary>
  4. /// 为swagger增加Authentication报文头
  5. /// </summary>
  6. /// <param name="option"></param>
  7. public static void AddAuthenticationHeader(this SwaggerGenOptions option)
  8. {
  9. option.AddSecurityDefinition("Authorization",
  10. new OpenApiSecurityScheme
  11. {
  12. Description = "Authorization header. \r\nExample:Bearer 12345ABCDE",
  13. Name = "Authorization",
  14. In = ParameterLocation.Header,
  15. Type = SecuritySchemeType.ApiKey,
  16. Scheme = "Authorization"
  17. }
  18. ); ;
  19. option.AddSecurityRequirement(new OpenApiSecurityRequirement()
  20. {
  21. {
  22. new OpenApiSecurityScheme
  23. {
  24. Reference=new OpenApiReference
  25. {
  26. Type=ReferenceType.SecurityScheme,
  27. Id="Authorization"
  28. },
  29. Scheme="oauth2",
  30. Name="Authorization",
  31. In=ParameterLocation.Header,
  32. },
  33. new List<string>()
  34. }
  35. });
  36. }
  37. }

5.创建IJwtService接口及实现JwtService类,其为构建token服务

  1. public interface IJwtService
  2. {
  3. string BuildToken(IEnumerable<Claim> claims, JwtOptions options);
  4. }
  1. public class JwtService : IJwtService
  2. {
  3. public string BuildToken(IEnumerable<Claim> claims, JwtOptions options)
  4. {
  5. //过期时间
  6. TimeSpan timeSpan = TimeSpan.FromSeconds(options.ExpireSeconds);//token过期时间
  7. var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(options.Key));//加密的token密钥
  8. var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);//签名证书,其值为securityKey和HmacSha256Signature算法
  9. var tokenDescriptor = new JwtSecurityToken(options.Issuer, options.Audience, claims, expires: DateTime.Now.Add(timeSpan), signingCredentials: credentials);//表示jwt token的描述信息,其值包括Issuer签发方,Audience接收方,Claims载荷,过期时间和签名证书
  10. return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);//使用该方法转换为字符串形式的jwt token返回
  11. }
  12. }

6.将上述服务尽数注册

  1. builder.Services.AddControllers();
  2. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  3. builder.Services.AddEndpointsApiExplorer();
  4. builder.Services.AddSwaggerGen();
  5. builder.Services.AddScoped<IJwtService, JwtService>();
  6. JwtOptions jwtOpt = builder.Configuration.GetSection("JWT").Get<JwtOptions>();
  7. builder.Services.AddJWTAuthentication(jwtOpt);
  8. builder.Services.Configure<SwaggerGenOptions>(c =>
  9. {
  10. c.AddAuthenticationHeader();
  11. });
  12. var app = builder.Build();
  13. app.UseSwagger();
  14. app.UseSwaggerUI();
  15. app.UseHttpsRedirection();
  16. app.UseAuthentication();//注意,一定得先启动这个
  17. app.UseAuthorization();
  18. //以下回答来自GPT
  19. //app.UseAuthentication()是启用身份验证中间件,它会验证请求中的身份信息,并将身份信息存储在HttpContext.User属性中。而app.UseAuthorization()是启用授权中间件,它会检查HttpContext.User中的身份信息是否有访问当前请求所需的权限。
  20. //一定要先启用身份验证中间件再启用授权中间件,因为授权中间件需要使用身份验证中间件存储的身份信息来进行权限验证。如果没有启用身份验证中间件,授权中间件将无法获取到身份信息,从而无法进行权限验证。
  21. app.MapControllers();
  22. app.Run();

7.在控制器中添加[ApiController]特性开启jwt鉴权,在登录接口中返回token

  1. [ApiController]
  2. [Route("[controller]/[action]")]
  3. [Authorize]
  4. public class WeatherForecastController : ControllerBase
  5. {
  6. private static readonly string[] Summaries = new[]
  7. {
  8. "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
  9. };
  10. private readonly ILogger<WeatherForecastController> _logger;
  11. //jwt服务
  12.  
  13. private readonly IJwtService _jwtService;
  14. private readonly IConfiguration _configuration;
  15. public WeatherForecastController(ILogger<WeatherForecastController> logger, IJwtService jwtService, IConfiguration configuration)
  16. {
  17. _logger = logger;
  18. _jwtService = jwtService;
  19. _configuration = configuration;
  20. }
  21. [HttpGet]
  22. public IEnumerable<WeatherForecast> Get()
  23. {
  24. return Enumerable.Range(1, 5).Select(index => new WeatherForecast
  25. {
  26. Date = DateTime.Now.AddDays(index),
  27. TemperatureC = Random.Shared.Next(-20, 55),
  28. Summary = Summaries[Random.Shared.Next(Summaries.Length)]
  29. })
  30. .ToArray();
  31. }
  32. //AllowAnonymous允许匿名访问
  33. [AllowAnonymous, HttpGet]
  34. public string GetToken()
  35. {
  36. var jwtopntion = _configuration.GetSection("JWT").Get<JwtOptions>();
  37. List<Claim> claims = new List<Claim>();
  38. claims.Add(new Claim(ClaimTypes.Name, "用户1"));
  39. claims.Add(new Claim(ClaimTypes.Role, "超级管理员"));
  40. return _jwtService.BuildToken(claims, jwtopntion);
  41. }
  42. }

效果测试

 

直接调用Get方法返回401,鉴权失败

 

 调用GetToken方法,取得token

 点击右上角绿色按钮

 value中输入的值为bearer,空一格,加上之前取得的token,点击授权

 调用成功

原文链接:https://www.cnblogs.com/SaoJian/p/17451001.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号