您现在的位置是:首页 > 技术教程 正文

C# ASP.NET Core Web API 身份授权(JWT)验证(一)

admin 阅读: 2024-03-30
后台-插件-广告管理-内容页头部广告(手机)

1.开发环境 VS2022,安装时记得勾选ASP.NET有关的都选上,建议全选,省的麻烦。

        

2.创建初始工程 TestApi (你自己的工程名称)。

 

 这就创建工程成功了,按 F5 则可以进行调试了。

而在项目中,我们不仅仅会用到基础的api功能,我们一般还会用到 身份授权(JWT)Redis缓存MySQL数据库 等,今天只讲身份授权(JWT)。后面文章将继续讲解其他两项。

--------------------添加 身份授权(JWT)--------------------

右键点击工程,选择 管理NuGet程序包 :

在 浏览 页面 搜索框 中输入 Microsoft.AspNetCore.Authentication.JwtBearer

点击安装即可(注意选择版本,选择大版本 6 即可):

 

 安装完成后,打开工程 appsettings.json 配置文件,添加JWT配置:

  1. "Jwt": {
  2. "SecretKey": "u6u^Bdob@OJ&KF2RcAB%ybsoy&2S7jhP^SW!q!Z^FK7eB7F8CcxIHsIh4Ll3pL^#",
  3. "Issuer": "WebAppIssuer",
  4. "Audience": "WebAppAudience"
  5. }

 下一步在工程目录下添加文件夹 Common :

 在Common 文件夹中添加 JWTHelper.cs 类:

 完整代码(其中命名空间 namespace TestApi.Common 改成你自己的即可 ):

  1. using Microsoft.IdentityModel.Tokens;
  2. using System.IdentityModel.Tokens.Jwt;
  3. using System.Security.Claims;
  4. using System.Text;
  5. namespace TestApi.Common
  6. {
  7. ///
  8. /// 授权JWT类
  9. ///
  10. public class JwtHelper
  11. {
  12. private readonly IConfiguration _configuration;
  13. ///
  14. /// Token配置
  15. ///
  16. ///
  17. public JwtHelper(IConfiguration configuration)
  18. {
  19. _configuration = configuration;
  20. }
  21. ///
  22. /// 创建Token 这里面可以保存自己想要的信息
  23. ///
  24. ///
  25. ///
  26. ///
  27. public string CreateToken(string username,string mobile)
  28. {
  29. // 1. 定义需要使用到的Claims
  30. var claims = new[]
  31. {
  32. new Claim("username", username),
  33. new Claim("mobile", mobile),
  34. /* 可以保存自己想要信息,传参进来即可
  35. new Claim("sex", "sex"),
  36. new Claim("limit", "limit"),
  37. new Claim("head_url", "xxxxx")
  38. */
  39. };
  40. // 2. 从 appsettings.json 中读取SecretKey
  41. var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));
  42. // 3. 选择加密算法
  43. var algorithm = SecurityAlgorithms.HmacSha256;
  44. // 4. 生成Credentials
  45. var signingCredentials = new SigningCredentials(secretKey, algorithm);
  46. // 5. 根据以上,生成token
  47. var jwtSecurityToken = new JwtSecurityToken(
  48. _configuration["Jwt:Issuer"], //Issuer
  49. _configuration["Jwt:Audience"], //Audience
  50. claims, //Claims,
  51. DateTime.Now, //notBefore
  52. DateTime.Now.AddSeconds(30), //expires
  53. signingCredentials //Credentials
  54. );
  55. // 6. 将token变为string
  56. var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
  57. return token;
  58. }
  59. }
  60. }

打开 Program.cs 文件,添加注册信息:

  1. #region JWT服务
  2. // 注册JWT服务
  3. builder.Services.AddSingleton(new JwtHelper(builder.Configuration));
  4. builder.Services.AddAuthentication(options =>
  5. {
  6. options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
  7. }
  8. ).AddJwtBearer(options =>
  9. {
  10. options.TokenValidationParameters = new TokenValidationParameters()
  11. {
  12. ValidateIssuer = true, //是否验证Issuer
  13. ValidIssuer = builder.Configuration["Jwt:Issuer"], //发行人Issuer
  14. ValidateAudience = true, //是否验证Audience
  15. ValidAudience = builder.Configuration["Jwt:Audience"], //订阅人Audience
  16. ValidateIssuerSigningKey = true, //是否验证SecurityKey
  17. IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:SecretKey"])), //SecurityKey
  18. ValidateLifetime = true, //是否验证失效时间
  19. ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
  20. RequireExpirationTime = true,
  21. };
  22. }
  23. );
  24. #endregion
  25. //记得要添加此句--注册服务
  26. app.UseAuthorization();

 

 添加 Models 文件夹,再UserInfo.cs 类:

完整代码如下:

  1. using System.ComponentModel.DataAnnotations;
  2. namespace TestApi.Models
  3. {
  4. public class UserInfo
  5. {
  6. ///
  7. /// 其中 [Required] 表示非空判断,其他自己研究百度
  8. ///
  9. [Required]
  10. public string UserName { get; set; }
  11. [Required]
  12. public string Password { get; set; }
  13. [Required]
  14. public string PhoneNumber { get; set; }
  15. }
  16. }

在Controllers文件夹中添加 API控制器 UserInfoController.cs

 完整代码:

  1. using Microsoft.AspNetCore.Mvc;
  2. using TestApi.Common;
  3. using TestApi.Models;
  4. namespace TestApi.Controllers
  5. {
  6. [Route("[controller]/[action]")]
  7. [ApiController]
  8. public class UserInfoController : ControllerBase
  9. {
  10. private readonly JwtHelper _jwt;
  11. ///
  12. /// 初始化
  13. ///
  14. ///
  15. public UserInfoController(JwtHelper jwtHelper)
  16. {
  17. _jwt = jwtHelper;
  18. }
  19. ///
  20. /// 获取Token
  21. ///
  22. ///
  23. [HttpPost]
  24. public IActionResult GetToken(UserInfo user)
  25. {
  26. //参数验证等等....
  27. if (string.IsNullOrEmpty(user.UserName))
  28. {
  29. return Ok("参数异常!");
  30. }
  31. //这里可以连接mysql数据库做账号密码验证
  32. //这里可以做Redis缓存验证等等
  33. //这里获取Token,当然,这里也可以选择传结构体过去
  34. var token = _jwt.CreateToken(user.UserName, user.PhoneNumber);
  35. return Ok(token);
  36. }
  37. ///
  38. /// 获取自己的详细信息,其中 [Authorize] 就表示要带Token才行
  39. ///
  40. ///
  41. [HttpPost]
  42. [Authorize]
  43. public IActionResult GetSelfInfo()
  44. {
  45. //执行到这里,就表示已经验证授权通过了
  46. /*
  47. * 这里返回个人信息有两种方式
  48. * 第一种:从Header中的Token信息反向解析出用户账号,再从数据库中查找返回
  49. * 第二种:从Header中的Token信息反向解析出用户账号信息直接返回,当然,在前面创建 Token时,要保存进使用到的Claims中。
  50. */
  51. return Ok("授权通过了!");
  52. }
  53. }
  54. }

 然后,就可以 F5 测试了:

下一篇文章将继续介绍Redis:

C# ASP.NET Core Web API Redis使用教程(二)_asp.net redis教程_蛋蛋の微笑的博客-CSDN博客

标签:
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

在线投稿:投稿 站长QQ:1888636

后台-插件-广告管理-内容页尾部广告(手机)
关注我们

扫一扫关注我们,了解最新精彩内容

搜索