当前位置:   article > 正文

在ASP.NET Core Web API 6中应用JWT访问令牌和刷新令牌_.net core jwt刷新token

.net core jwt刷新token

目录

访问令牌与刷新令牌

开始教程

数据库准备

项目创建

实体框架核心和DbContext

实体

RefreshToken

Task

User

DbContext

PasswordHashHelper

实现JWT身份验证

用于构建访问令牌和刷新令牌的令牌助手

请求和响应

LoginRequest

RefreshTokenRequest

SignupRequest

TaskRequest

BaseResponse

DeleteTaskResponse

GetTasksResponse

LogoutResponse

SaveTaskResponse

SignupResponse

TaskResponse

TokenResponse

ValidateRefreshTokenResponse

接口

ITokenService

IUserService

ITasksInterface

服务

TokenService

UserService

TaskService

控制器

BaseApiController

UsersController

TasksController

在Postman上进行测试

refresh_token端点

恶意或已注销的用户

总结


在本教程中,我们将构建一个简单、安全且可靠的RESTful API项目,以正确验证用户并授权他们对API执行操作。

在本教程中,我们将学习如何在ASP.NET Core Web API 6中应用JWT访问令牌和刷新令牌。我们将构建一个简单、安全且可靠的RESTful API项目来正确验证用户并授权他们对API执行操作。

我们将使用最新最好的Visual Studio 2022社区版来构建我们的ASP.NET Core Web API,使用最快的.NET标准框架,即.NET 6C# 10

好消息是VS 2022捆绑了最新版本的.NETC#,因此您不必担心搜索和安装它们中的任何一个。因此,如果您还没有VS 2022,请确保下载并安装Visual Studio 2022,以便我们可以开始使用我们的教程在ASP.NET Core Web API 6中应用JWT访问令牌和刷新令牌。

在之前的教程中,我们学习了如何使用JWT身份验证来保护ASP.NET Core Web API,但这只是使用访问令牌。现在,这是一个从头开始构建的新教程,解释了使用访问令牌和刷新令牌时有关JWT身份验证的所有内容。

访问令牌与刷新令牌

Authorization标头中提供访问令牌时,我们使用访问令牌授予用户访问服务器上某些资源的适当授权。访问令牌通常是短期和签名的,对于JWT令牌,这将包括签名、声明、标头。

另一方面,刷新令牌通常是只能用于刷新访问令牌的引用。此类令牌通常保存在后端存储中,可用于撤销用户的访问权限,例如,不再有资格访问这些资源或恶意用户窃取访问令牌的情况。

在这种情况下,您只需删除这些设备的刷新令牌,因此一旦他们的访问令牌过期,他们将无法使用撤销的刷新令牌更新(刷新)它,因为他们曾经有效的刷新令牌不再有效,他们将无法再访问您的资源。因此,用户将在应用程序或Web中注销,因此他们必须重新登录并再次完成通常的登录过程。

现在已经足够僵硬的文本了,让我们直接开始构建我们的API,这些API将使用NET 6中的ASP.NET Core Web API使用访问令牌和刷新令牌来实现JWT身份验证。

开始教程

我们将构建一个简单的任务管理系统,允许经过身份验证的用户管理自己的任务。这只是任务管理系统的简单基本表示。

随意从Githubfork并为您的个人项目构建它。

数据库准备

在我的大部分教程中,我使用SQL Server Express创建所需的数据库和表。因此,请确保下载并安装最新版本的SQL Server Management StudioSQL Server Express

安装两者后,打开SQL Server Management Studio并连接到安装了SQL Server Express的本地计算机:

在对象资源管理器中,右键单击数据库并选择创建新数据库,为其命名TasksDb,如下所示:

然后运行以下命令来创建表并使用本教程所需的数据填充它:

  1. USE [TasksDb]
  2. GO
  3. /****** Object: Table [dbo].[RefreshToken] Script Date: 1/18/2022 6:10:48 PM ******/
  4. SET ANSI_NULLS ON
  5. GO
  6. SET QUOTED_IDENTIFIER ON
  7. GO
  8. CREATE TABLE [dbo].[RefreshToken](
  9. [Id] [int] IDENTITY(1,1) NOT NULL,
  10. [UserId] [int] NOT NULL,
  11. [TokenHash] [nvarchar](1000) NOT NULL,
  12. [TokenSalt] [nvarchar](50) NOT NULL,
  13. [TS] [smalldatetime] NOT NULL,
  14. [ExpiryDate] [smalldatetime] NOT NULL,
  15. CONSTRAINT [PK_RefreshToken] PRIMARY KEY CLUSTERED
  16. (
  17. [Id] ASC
  18. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
  19. ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
  20. ) ON [PRIMARY]
  21. GO
  22. /****** Object: Table [dbo].[Task] Script Date: 1/18/2022 6:10:48 PM ******/
  23. SET ANSI_NULLS ON
  24. GO
  25. SET QUOTED_IDENTIFIER ON
  26. GO
  27. CREATE TABLE [dbo].[Task](
  28. [Id] [int] IDENTITY(1,1) NOT NULL,
  29. [UserId] [int] NOT NULL,
  30. [Name] [nvarchar](100) NOT NULL,
  31. [IsCompleted] [bit] NOT NULL,
  32. [TS] [smalldatetime] NOT NULL,
  33. CONSTRAINT [PK_Task] PRIMARY KEY CLUSTERED
  34. (
  35. [Id] ASC
  36. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
  37. ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
  38. ) ON [PRIMARY]
  39. GO
  40. /****** Object: Table [dbo].[User] Script Date: 1/18/2022 6:10:48 PM ******/
  41. SET ANSI_NULLS ON
  42. GO
  43. SET QUOTED_IDENTIFIER ON
  44. GO
  45. CREATE TABLE [dbo].[User](
  46. [Id] [int] IDENTITY(1,1) NOT NULL,
  47. [Email] [nvarchar](50) NOT NULL,
  48. [Password] [nvarchar](255) NOT NULL,
  49. [PasswordSalt] [nvarchar](255) NOT NULL,
  50. [FirstName] [nvarchar](255) NOT NULL,
  51. [LastName] [nvarchar](255) NOT NULL,
  52. [TS] [smalldatetime] NOT NULL,
  53. [Active] [bit] NOT NULL,
  54. CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED
  55. (
  56. [Id] ASC
  57. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
  58. ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
  59. ) ON [PRIMARY]
  60. GO
  61. SET IDENTITY_INSERT [dbo].[Task] ON
  62. GO
  63. INSERT [dbo].[Task] ([Id], [UserId], [Name], [IsCompleted], [TS]) _
  64. VALUES (1, 1, N'Blog about Access Token and Refresh Token Authentication', _
  65. 1, CAST(N'2022-01-14T00:00:00' AS SmallDateTime))
  66. GO
  67. INSERT [dbo].[Task] ([Id], [UserId], [Name], [IsCompleted], [TS]) _
  68. VALUES (3, 1, N'Vaccum the House', 0, CAST(N'2022-01-14T00:00:00' AS SmallDateTime))
  69. GO
  70. INSERT [dbo].[Task] ([Id], [UserId], [Name], [IsCompleted], [TS]) _
  71. VALUES (4, 1, N'Farmers Market Shopping', 0, CAST(N'2022-01-14T00:00:00' AS SmallDateTime))
  72. GO
  73. INSERT [dbo].[Task] ([Id], [UserId], [Name], [IsCompleted], [TS]) _
  74. VALUES (5, 1, N'Practice Juggling', 0, CAST(N'2022-01-15T00:00:00' AS SmallDateTime))
  75. GO
  76. SET IDENTITY_INSERT [dbo].[Task] OFF
  77. GO
  78. SET IDENTITY_INSERT [dbo].[User] ON
  79. GO
  80. INSERT [dbo].[User] ([Id], [Email], [Password], [PasswordSalt], [FirstName], [LastName], _
  81. [TS], [Active]) VALUES (1, N'coding@codingsonata.com', _
  82. N'miLgvYoSVrotOON6/lRp8ACrrbAxCPCmsrsy355x/DI=', _
  83. N'L5hziA8V93SNGTlYdz+meS0B6DPzB3IwsRhDf1vO1GM=', N'Coding', N'Sonata', _
  84. CAST(N'2022-01-14T00:00:00' AS SmallDateTime), 1)
  85. GO
  86. INSERT [dbo].[User] ([Id], [Email], [Password], [PasswordSalt], [FirstName], [LastName], _
  87. [TS], [Active]) VALUES (2, N'test@codingsonata.com', _
  88. N'Fm7/SI9lYAFglzWXLD5oLz0cuq00MQmPkzDZ+nDZNmc=', _
  89. N'kjgIDmRKgUbbWypCOOUHuxlQzZAszdEKw358ds4Xyc4=', N'test', N'postman', _
  90. CAST(N'2022-01-16T14:23:00' AS SmallDateTime), 1)
  91. GO
  92. SET IDENTITY_INSERT [dbo].[User] OFF
  93. GO
  94. ALTER TABLE [dbo].[RefreshToken] WITH CHECK ADD CONSTRAINT [FK_RefreshToken_User] _
  95. FOREIGN KEY([UserId])
  96. REFERENCES [dbo].[User] ([Id])
  97. GO
  98. ALTER TABLE [dbo].[RefreshToken] CHECK CONSTRAINT [FK_RefreshToken_User]
  99. GO
  100. ALTER TABLE [dbo].[Task] WITH CHECK ADD CONSTRAINT [FK_Task_User] FOREIGN KEY([UserId])
  101. REFERENCES [dbo].[User] ([Id])
  102. GO
  103. ALTER TABLE [dbo].[Task] CHECK CONSTRAINT [FK_Task_User]
  104. GO

项目创建

打开Visual Studio 2022,并创建一个ASP.NET Core Web API类型的新项目:

给它起一个名字,如TasksApi

然后选择.NET 6.0并创建项目:

VS完成项目的初始化后,按F5对模板项目进行初始运行,以确保它工作正常。

现在,让我们从模板项目中删除一些不需要的类。从解决方案资源管理器,删除WeatherForecastControllerWeatherForecast文件。

实体框架核心和DbContext

让我们为EF CoreEF Core SQL添加Nuget包:

实体

现在让我们创建将通过EF Core DbContext类绑定到数据库表的所需实体。

我们将创建三个映射到Tasks数据库的实体。

RefreshToken

  1. // <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
  2. #nullable disable
  3. namespace TasksApi
  4. {
  5. public partial class RefreshToken
  6. {
  7. public int Id { get; set; }
  8. public int UserId { get; set; }
  9. public string TokenHash { get; set; }
  10. public string TokenSalt { get; set; }
  11. public DateTime Ts { get; set; }
  12. public DateTime ExpiryDate { get; set; }
  13. public virtual User User { get; set; }
  14. }
  15. }

Task

  1. // <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
  2. #nullable disable
  3. using System;
  4. using System.Collections.Generic;
  5. namespace TasksApi
  6. {
  7. public partial class Task
  8. {
  9. public int Id { get; set; }
  10. public int UserId { get; set; }
  11. public string Name { get; set; }
  12. public bool IsCompleted { get; set; }
  13. public DateTime Ts { get; set; }
  14. public virtual User User { get; set; }
  15. }
  16. }

User

  1. // <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
  2. #nullable disable
  3. using System;
  4. using System.Collections.Generic;
  5. namespace TasksApi
  6. {
  7. public partial class User
  8. {
  9. public User()
  10. {
  11. RefreshTokens = new HashSet<RefreshToken>();
  12. Tasks = new HashSet<Task>();
  13. }
  14. public int Id { get; set; }
  15. public string Email { get; set; }
  16. public string Password { get; set; }
  17. public string PasswordSalt { get; set; }
  18. public string FirstName { get; set; }
  19. public string LastName { get; set; }
  20. public DateTime Ts { get; set; }
  21. public bool Active { get; set; }
  22. public virtual ICollection<RefreshToken> RefreshTokens { get; set; }
  23. public virtual ICollection<Task> Tasks { get; set; }
  24. }
  25. }

DbContext

现在让我们添加将从EF CoreDbContext类继承的TasksDbContext类:

  1. // <auto-generated> This file has been auto generated by EF Core Power Tools. </auto-generated>
  2. #nullable disable
  3. using Microsoft.EntityFrameworkCore;
  4. namespace TasksApi
  5. {
  6. public partial class TasksDbContext : DbContext
  7. {
  8. public TasksDbContext()
  9. {
  10. }
  11. public TasksDbContext(DbContextOptions<TasksDbContext> options)
  12. : base(options)
  13. {
  14. }
  15. public virtual DbSet<RefreshToken> RefreshTokens { get; set; }
  16. public virtual DbSet<Task> Tasks { get; set; }
  17. public virtual DbSet<User> Users { get; set; }
  18. protected override void OnModelCreating(ModelBuilder modelBuilder)
  19. {
  20. modelBuilder.Entity<RefreshToken>(entity =>
  21. {
  22. entity.Property(e => e.ExpiryDate).HasColumnType("smalldatetime");
  23. entity.Property(e => e.TokenHash)
  24. .IsRequired()
  25. .HasMaxLength(1000);
  26. entity.Property(e => e.TokenSalt)
  27. .IsRequired()
  28. .HasMaxLength(1000);
  29. entity.Property(e => e.Ts)
  30. .HasColumnType("smalldatetime")
  31. .HasColumnName("TS");
  32. entity.HasOne(d => d.User)
  33. .WithMany(p => p.RefreshTokens)
  34. .HasForeignKey(d => d.UserId)
  35. .OnDelete(DeleteBehavior.ClientSetNull)
  36. .HasConstraintName("FK_RefreshToken_User");
  37. entity.ToTable("RefreshToken");
  38. });
  39. modelBuilder.Entity<Task>(entity =>
  40. {
  41. entity.Property(e => e.Name)
  42. .IsRequired()
  43. .HasMaxLength(100);
  44. entity.Property(e => e.Ts)
  45. .HasColumnType("smalldatetime")
  46. .HasColumnName("TS");
  47. entity.HasOne(d => d.User)
  48. .WithMany(p => p.Tasks)
  49. .HasForeignKey(d => d.UserId)
  50. .OnDelete(DeleteBehavior.ClientSetNull)
  51. .HasConstraintName("FK_Task_User");
  52. entity.ToTable("Task");
  53. });
  54. modelBuilder.Entity<User>(entity =>
  55. {
  56. entity.Property(e => e.Email)
  57. .IsRequired()
  58. .HasMaxLength(50);
  59. entity.Property(e => e.FirstName)
  60. .IsRequired()
  61. .HasMaxLength(255);
  62. entity.Property(e => e.LastName)
  63. .IsRequired()
  64. .HasMaxLength(255);
  65. entity.Property(e => e.Password)
  66. .IsRequired()
  67. .HasMaxLength(255);
  68. entity.Property(e => e.PasswordSalt)
  69. .IsRequired()
  70. .HasMaxLength(255);
  71. entity.Property(e => e.Ts)
  72. .HasColumnType("smalldatetime")
  73. .HasColumnName("TS");
  74. entity.ToTable("User");
  75. });
  76. OnModelCreatingPartial(modelBuilder);
  77. }
  78. partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
  79. }
  80. }

在您的program.cs文件中,在调用builder.build()之前添加以下内容:

  1. builder.Services.AddDbContext<TasksDbContext>(options => options.UseSqlServer
  2. (builder.Configuration.GetConnectionString("TasksDbConnectionString")));

然后在您的appsettings.json中,确保包含数据库的连接string

  1. {
  2. "ConnectionStrings": {
  3. "TasksDbConnectionString": "Server=Home\\SQLEXPRESS;Database=TasksDb;
  4. Trusted_Connection=True;MultipleActiveResultSets=true"
  5. },
  6. "Logging": {
  7. "LogLevel": {
  8. "Default": "Information",
  9. "Microsoft.AspNetCore": "Warning"
  10. }
  11. },
  12. "AllowedHosts": "*"
  13. }

注意:我使用了出色的扩展EF Core Power Tools,它以一种神奇的方式将整个数据库结构和关系转换为整洁和适当的DbContext实体和配置。

您可以从Extensions选项卡 -> Manage Extensions of your Visual Studio 2022安装它

如果您遵循设计优先模型先构建数据库,然后再构建EF Core映射,我强烈建议您使用这个快速可靠的工具来执行此类操作,从而提高您的工作效率并减少手动创建实体和配置可能引入的错误。

PasswordHashHelper

为了将密码保存在数据库中,我们需要使用安全哈希HMAC 256和来自256位大小的安全随机字节的盐,这样我们就可以保护有价值的用户密码免受那些讨厌的潜伏小偷的侵害!

  1. using Microsoft.AspNetCore.Cryptography.KeyDerivation;
  2. using System.Security.Cryptography;
  3. namespace TasksApi.Helpers
  4. {
  5. public class PasswordHelper
  6. {
  7. public static byte[] GetSecureSalt()
  8. {
  9. // Starting .NET 6, the Class RNGCryptoServiceProvider is obsolete,
  10. // so now we have to use the RandomNumberGenerator Class
  11. // to generate a secure random number bytes
  12. return RandomNumberGenerator.GetBytes(32);
  13. }
  14. public static string HashUsingPbkdf2(string password, byte[] salt)
  15. {
  16. byte[] derivedKey = KeyDerivation.Pbkdf2
  17. (password, salt, KeyDerivationPrf.HMACSHA256, iterationCount: 100000, 32);
  18. return Convert.ToBase64String(derivedKey);
  19. }
  20. }
  21. }

我们还将使用这些辅助方法以散列格式将刷新令牌与其关联的盐一起保存在数据库中。

实现JWT身份验证

让我们添加所需的JWT承载包:

用于构建访问令牌和刷新令牌的令牌助手

现在让我们添加TokenHelper,其中将包括两种方法来生成基于JWT的访问令牌,另一种方法来生成基于32字节的刷新令牌:

  1. using Microsoft.IdentityModel.Tokens;
  2. using System.IdentityModel.Tokens.Jwt;
  3. using System.Security.Claims;
  4. using System.Security.Cryptography;
  5. namespace TasksApi.Helpers
  6. {
  7. public class TokenHelper
  8. {
  9. public const string Issuer = "http://codingsonata.com";
  10. public const string Audience = "http://codingsonata.com";
  11. public const string Secret =
  12. "p0GXO6VuVZLRPef0tyO9jCqK4uZufDa6LP4n8Gj+8hQPB30f94pFiECAnPeMi5N6VT3/uscoGH7+zJrv4AuuPg==";
  13. public static async Task<string> GenerateAccessToken(int userId)
  14. {
  15. var tokenHandler = new JwtSecurityTokenHandler();
  16. var key = Convert.FromBase64String(Secret);
  17. var claimsIdentity = new ClaimsIdentity(new[] {
  18. new Claim(ClaimTypes.NameIdentifier, userId.ToString())
  19. });
  20. var signingCredentials = new SigningCredentials
  21. (new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature);
  22. var tokenDescriptor = new SecurityTokenDescriptor
  23. {
  24. Subject = claimsIdentity,
  25. Issuer = Issuer,
  26. Audience = Audience,
  27. Expires = DateTime.Now.AddMinutes(15),
  28. SigningCredentials = signingCredentials,
  29. };
  30. var securityToken = tokenHandler.CreateToken(tokenDescriptor);
  31. return await System.Threading.Tasks.Task.Run(() =>
  32. tokenHandler.WriteToken(securityToken));
  33. }
  34. public static async Task<string> GenerateRefreshToken()
  35. {
  36. var secureRandomBytes = new byte[32];
  37. using var randomNumberGenerator = RandomNumberGenerator.Create();
  38. await System.Threading.Tasks.Task.Run(() =>
  39. randomNumberGenerator.GetBytes(secureRandomBytes));
  40. var refreshToken = Convert.ToBase64String(secureRandomBytes);
  41. return refreshToken;
  42. }
  43. }
  44. }

现在让我们确保在program.cs文件中将所需的身份验证和授权中间件添加到管道中:

builder.build方法之前添加以下内容:

  1. builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  2. .AddJwtBearer(options =>
  3. {
  4. options.TokenValidationParameters = new TokenValidationParameters
  5. {
  6. ValidateIssuer = true,
  7. ValidateAudience = true,
  8. ValidateIssuerSigningKey = true,
  9. ValidIssuer = TokenHelper.Issuer,
  10. ValidAudience = TokenHelper.Audience,
  11. IssuerSigningKey = new SymmetricSecurityKey
  12. (Convert.FromBase64String(TokenHelper.Secret))
  13. };
  14. });
  15. builder.Services.AddAuthorization();

然后在该app.run方法之前,确保应用程序将使用这两个中间件来验证和授权您的用户:

  1. app.UseAuthentication();
  2. app.UseAuthorization();

请求和响应

始终建议您接受和返回结构化对象而不是单独的数据,这就是为什么我们将准备一些RequestResponse类,我们将在整个API中使用它们:

让我们添加以下请求类:

LoginRequest

  1. namespace TasksApi.Requests
  2. {
  3. public class LoginRequest
  4. {
  5. public string Email { get; set; }
  6. public string Password { get; set; }
  7. }
  8. }

RefreshTokenRequest

  1. namespace TasksApi.Requests
  2. {
  3. public class RefreshTokenRequest
  4. {
  5. public int UserId { get; set; }
  6. public string RefreshToken { get; set; }
  7. }
  8. }

SignupRequest

  1. using System.ComponentModel.DataAnnotations;
  2. namespace TasksApi.Requests
  3. {
  4. public class SignupRequest
  5. {
  6. [Required]
  7. [EmailAddress]
  8. public string Email { get; set; }
  9. [Required]
  10. public string Password { get; set; }
  11. [Required]
  12. public string ConfirmPassword { get; set; }
  13. [Required]
  14. public string FirstName { get; set; }
  15. [Required]
  16. public string LastName { get; set; }
  17. [Required]
  18. public DateTime Ts { get; set; }
  19. }
  20. }

TaskRequest

  1. namespace TasksApi.Requests
  2. {
  3. public class TaskRequest
  4. {
  5. public string Name { get; set; }
  6. public bool IsCompleted { get; set; }
  7. public DateTime Ts { get; set; }
  8. }
  9. }

现在让我们添加响应类,这些类将用于为调用APIUI客户端返回结构化响应:

BaseResponse

这将使用一个基类,以便其他响应类可以继承并扩展它们的属性:

  1. using System.Text.Json.Serialization;
  2. namespace TasksApi.Responses
  3. {
  4. public abstract class BaseResponse
  5. {
  6. [JsonIgnore()]
  7. public bool Success { get; set; }
  8. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  9. public string ErrorCode { get; set; }
  10. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
  11. public string Error { get; set; }
  12. }
  13. }

DeleteTaskResponse

  1. using System.Text.Json.Serialization;
  2. namespace TasksApi.Responses
  3. {
  4. public class DeleteTaskResponse : BaseResponse
  5. {
  6. [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
  7. public int TaskId { get; set; }
  8. }
  9. }

GetTasksResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class GetTasksResponse : BaseResponse
  4. {
  5. public List<Task> Tasks { get; set; }
  6. }
  7. }

LogoutResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class LogoutResponse : BaseResponse
  4. {
  5. }
  6. }

SaveTaskResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class SaveTaskResponse : BaseResponse
  4. {
  5. public Task Task { get; set; }
  6. }
  7. }

SignupResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class SignupResponse : BaseResponse
  4. {
  5. public string Email { get; set; }
  6. }
  7. }

TaskResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class TaskResponse
  4. {
  5. public int Id { get; set; }
  6. public string Name { get; set; }
  7. public bool IsCompleted { get; set; }
  8. public DateTime Ts { get; set; }
  9. }
  10. }

TokenResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class TokenResponse: BaseResponse
  4. {
  5. public string AccessToken { get; set; }
  6. public string RefreshToken { get; set; }
  7. }
  8. }

ValidateRefreshTokenResponse

  1. namespace TasksApi.Responses
  2. {
  3. public class ValidateRefreshTokenResponse : BaseResponse
  4. {
  5. public int UserId { get; set; }
  6. }
  7. }

接口

我们将定义三个将在服务中实现的接口。接口是控制器需要用来处理相关业务逻辑和数据库调用的抽象,每个接口都将在运行时注入的服务中实现。

这是一种非常有用的策略(或设计模式),可以使您的API松散耦合且易于测试。

ITokenService

  1. using TasksApi.Requests;
  2. using TasksApi.Responses;
  3. namespace TasksApi.Interfaces
  4. {
  5. public interface ITokenService
  6. {
  7. Task<Tuple<string, string>> GenerateTokensAsync(int userId);
  8. Task<ValidateRefreshTokenResponse> ValidateRefreshTokenAsync
  9. (RefreshTokenRequest refreshTokenRequest);
  10. Task<bool> RemoveRefreshTokenAsync(User user);
  11. }
  12. }

IUserService

  1. using TasksApi.Requests;
  2. using TasksApi.Responses;
  3. namespace TasksApi.Interfaces
  4. {
  5. public interface IUserService
  6. {
  7. Task<TokenResponse> LoginAsync(LoginRequest loginRequest);
  8. Task<SignupResponse> SignupAsync(SignupRequest signupRequest);
  9. Task<LogoutResponse> LogoutAsync(int userId);
  10. }
  11. }

ITasksInterface

  1. using TasksApi.Responses;
  2. namespace TasksApi.Interfaces
  3. {
  4. public interface ITaskService
  5. {
  6. Task<GetTasksResponse> GetTasks(int userId);
  7. Task<SaveTaskResponse> SaveTask(Task task);
  8. Task<DeleteTaskResponse> DeleteTask(int taskId, int userId);
  9. }
  10. }

服务

服务充当你的控制器和你的DbContext之间的中间层,它还包括控制器不应该关心的任何与业务相关的逻辑。服务实现接口。

我们将添加三个服务:

TokenService

这将包括生成令牌、验证和删除刷新令牌的方法:

  1. using Microsoft.EntityFrameworkCore;
  2. using TasksApi.Helpers;
  3. using TasksApi.Interfaces;
  4. using TasksApi.Requests;
  5. using TasksApi.Responses;
  6. namespace TasksApi.Services
  7. {
  8. public class TokenService : ITokenService
  9. {
  10. private readonly TasksDbContext tasksDbContext;
  11. public TokenService(TasksDbContext tasksDbContext)
  12. {
  13. this.tasksDbContext = tasksDbContext;
  14. }
  15. public async Task<Tuple<string, string>> GenerateTokensAsync(int userId)
  16. {
  17. var accessToken = await TokenHelper.GenerateAccessToken(userId);
  18. var refreshToken = await TokenHelper.GenerateRefreshToken();
  19. var userRecord = await tasksDbContext.Users.Include
  20. (o => o.RefreshTokens).FirstOrDefaultAsync(e => e.Id == userId);
  21. if (userRecord == null)
  22. {
  23. return null;
  24. }
  25. var salt = PasswordHelper.GetSecureSalt();
  26. var refreshTokenHashed = PasswordHelper.HashUsingPbkdf2(refreshToken, salt);
  27. if (userRecord.RefreshTokens != null && userRecord.RefreshTokens.Any())
  28. {
  29. await RemoveRefreshTokenAsync(userRecord);
  30. }
  31. userRecord.RefreshTokens?.Add(new RefreshToken
  32. {
  33. ExpiryDate = DateTime.Now.AddDays(30),
  34. Ts = DateTime.Now,
  35. UserId = userId,
  36. TokenHash = refreshTokenHashed,
  37. TokenSalt = Convert.ToBase64String(salt)
  38. });
  39. await tasksDbContext.SaveChangesAsync();
  40. var token = new Tuple<string, string>(accessToken, refreshToken);
  41. return token;
  42. }
  43. public async Task<bool> RemoveRefreshTokenAsync(User user)
  44. {
  45. var userRecord = await tasksDbContext.Users.Include
  46. (o => o.RefreshTokens).FirstOrDefaultAsync(e => e.Id == user.Id);
  47. if (userRecord == null)
  48. {
  49. return false;
  50. }
  51. if (userRecord.RefreshTokens != null && userRecord.RefreshTokens.Any())
  52. {
  53. var currentRefreshToken = userRecord.RefreshTokens.First();
  54. tasksDbContext.RefreshTokens.Remove(currentRefreshToken);
  55. }
  56. return false;
  57. }
  58. public async Task<ValidateRefreshTokenResponse> ValidateRefreshTokenAsync
  59. (RefreshTokenRequest refreshTokenRequest)
  60. {
  61. var refreshToken = await tasksDbContext.RefreshTokens.FirstOrDefaultAsync
  62. (o => o.UserId == refreshTokenRequest.UserId);
  63. var response = new ValidateRefreshTokenResponse();
  64. if (refreshToken == null)
  65. {
  66. response.Success = false;
  67. response.Error = "Invalid session or user is already logged out";
  68. response.ErrorCode = "R02";
  69. return response;
  70. }
  71. var refreshTokenToValidateHash = PasswordHelper.HashUsingPbkdf2
  72. (refreshTokenRequest.RefreshToken,
  73. Convert.FromBase64String(refreshToken.TokenSalt));
  74. if (refreshToken.TokenHash != refreshTokenToValidateHash)
  75. {
  76. response.Success = false;
  77. response.Error = "Invalid refresh token";
  78. response.ErrorCode = "R03";
  79. return response;
  80. }
  81. if (refreshToken.ExpiryDate < DateTime.Now)
  82. {
  83. response.Success = false;
  84. response.Error = "Refresh token has expired";
  85. response.ErrorCode = "R04";
  86. return response;
  87. }
  88. response.Success = true;
  89. response.UserId = refreshToken.UserId;
  90. return response;
  91. }
  92. }
  93. }

UserService

这将包括与登录、注销和注册相关的方法:

  1. using Microsoft.EntityFrameworkCore;
  2. using TasksApi.Helpers;
  3. using TasksApi.Interfaces;
  4. using TasksApi.Requests;
  5. using TasksApi.Responses;
  6. namespace TasksApi.Services
  7. {
  8. public class UserService : IUserService
  9. {
  10. private readonly TasksDbContext tasksDbContext;
  11. private readonly ITokenService tokenService;
  12. public UserService(TasksDbContext tasksDbContext, ITokenService tokenService)
  13. {
  14. this.tasksDbContext = tasksDbContext;
  15. this.tokenService = tokenService;
  16. }
  17. public async Task<TokenResponse> LoginAsync(LoginRequest loginRequest)
  18. {
  19. var user = tasksDbContext.Users.SingleOrDefault
  20. (user => user.Active && user.Email == loginRequest.Email);
  21. if (user == null)
  22. {
  23. return new TokenResponse
  24. {
  25. Success = false,
  26. Error = "Email not found",
  27. ErrorCode = "L02"
  28. };
  29. }
  30. var passwordHash = PasswordHelper.HashUsingPbkdf2
  31. (loginRequest.Password, Convert.FromBase64String(user.PasswordSalt));
  32. if (user.Password != passwordHash)
  33. {
  34. return new TokenResponse
  35. {
  36. Success = false,
  37. Error = "Invalid Password",
  38. ErrorCode = "L03"
  39. };
  40. }
  41. var token = await System.Threading.Tasks.Task.Run(() =>
  42. tokenService.GenerateTokensAsync(user.Id));
  43. return new TokenResponse
  44. {
  45. Success = true,
  46. AccessToken = token.Item1,
  47. RefreshToken = token.Item2
  48. };
  49. }
  50. public async Task<LogoutResponse> LogoutAsync(int userId)
  51. {
  52. var refreshToken = await tasksDbContext.RefreshTokens.FirstOrDefaultAsync
  53. (o => o.UserId == userId);
  54. if (refreshToken == null)
  55. {
  56. return new LogoutResponse { Success = true };
  57. }
  58. tasksDbContext.RefreshTokens.Remove(refreshToken);
  59. var saveResponse = await tasksDbContext.SaveChangesAsync();
  60. if (saveResponse >= 0)
  61. {
  62. return new LogoutResponse { Success = true };
  63. }
  64. return new LogoutResponse { Success = false,
  65. Error = "Unable to logout user", ErrorCode = "L04" };
  66. }
  67. public async Task<SignupResponse> SignupAsync(SignupRequest signupRequest)
  68. {
  69. var existingUser = await tasksDbContext.Users.SingleOrDefaultAsync
  70. (user => user.Email == signupRequest.Email);
  71. if (existingUser != null)
  72. {
  73. return new SignupResponse
  74. {
  75. Success = false,
  76. Error = "User already exists with the same email",
  77. ErrorCode = "S02"
  78. };
  79. }
  80. if (signupRequest.Password != signupRequest.ConfirmPassword) {
  81. return new SignupResponse
  82. {
  83. Success = false,
  84. Error = "Password and confirm password do not match",
  85. ErrorCode = "S03"
  86. };
  87. }
  88. if (signupRequest.Password.Length <= 7) // This can be more complicated than
  89. // only length, you can check on alphanumeric and or special characters
  90. {
  91. return new SignupResponse
  92. {
  93. Success = false,
  94. Error = "Password is weak",
  95. ErrorCode = "S04"
  96. };
  97. }
  98. var salt = PasswordHelper.GetSecureSalt();
  99. var passwordHash = PasswordHelper.HashUsingPbkdf2(signupRequest.Password, salt);
  100. var user = new User
  101. {
  102. Email = signupRequest.Email,
  103. Password = passwordHash,
  104. PasswordSalt = Convert.ToBase64String(salt),
  105. FirstName = signupRequest.FirstName,
  106. LastName = signupRequest.LastName,
  107. Ts = signupRequest.Ts,
  108. Active = true // You can save is false and send confirmation email
  109. // to the user, then once the user confirms the email you can make it true
  110. };
  111. await tasksDbContext.Users.AddAsync(user);
  112. var saveResponse = await tasksDbContext.SaveChangesAsync();
  113. if (saveResponse >= 0)
  114. {
  115. return new SignupResponse { Success = true, Email = user.Email };
  116. }
  117. return new SignupResponse
  118. {
  119. Success = false,
  120. Error = "Unable to save the user",
  121. ErrorCode = "S05"
  122. };
  123. }
  124. }
  125. }

TaskService

这包括添加、删除和获取任务的方法:

  1. using Microsoft.EntityFrameworkCore;
  2. using TasksApi.Interfaces;
  3. using TasksApi.Responses;
  4. namespace TasksApi.Services
  5. {
  6. public class TaskService : ITaskService
  7. {
  8. private readonly TasksDbContext tasksDbContext;
  9. public TaskService(TasksDbContext tasksDbContext)
  10. {
  11. this.tasksDbContext = tasksDbContext;
  12. }
  13. public async Task<DeleteTaskResponse> DeleteTask(int taskId, int userId)
  14. {
  15. var task = await tasksDbContext.Tasks.FindAsync(taskId);
  16. if (task == null)
  17. {
  18. return new DeleteTaskResponse
  19. {
  20. Success = false,
  21. Error = "Task not found",
  22. ErrorCode = "T01"
  23. };
  24. }
  25. if (task.UserId != userId)
  26. {
  27. return new DeleteTaskResponse
  28. {
  29. Success = false,
  30. Error = "You don't have access to delete this task",
  31. ErrorCode = "T02"
  32. };
  33. }
  34. tasksDbContext.Tasks.Remove(task);
  35. var saveResponse = await tasksDbContext.SaveChangesAsync();
  36. if (saveResponse >= 0)
  37. {
  38. return new DeleteTaskResponse
  39. {
  40. Success = true,
  41. TaskId = task.Id
  42. };
  43. }
  44. return new DeleteTaskResponse
  45. {
  46. Success = false,
  47. Error = "Unable to delete task",
  48. ErrorCode = "T03"
  49. };
  50. }
  51. public async Task<GetTasksResponse> GetTasks(int userId)
  52. {
  53. var tasks = await tasksDbContext.Tasks.Where
  54. (o => o.UserId == userId).ToListAsync();
  55. if (tasks.Count == 0)
  56. {
  57. return new GetTasksResponse
  58. {
  59. Success = false,
  60. Error = "No tasks found for this user",
  61. ErrorCode = "T04"
  62. };
  63. }
  64. return new GetTasksResponse { Success = true, Tasks = tasks };
  65. }
  66. public async Task<SaveTaskResponse> SaveTask(Task task)
  67. {
  68. await tasksDbContext.Tasks.AddAsync(task);
  69. var saveResponse = await tasksDbContext.SaveChangesAsync();
  70. if (saveResponse >= 0)
  71. {
  72. return new SaveTaskResponse
  73. {
  74. Success = true,
  75. Task = task
  76. };
  77. }
  78. return new SaveTaskResponse
  79. {
  80. Success = false,
  81. Error = "Unable to save task",
  82. ErrorCode = "T05"
  83. };
  84. }
  85. }
  86. }

现在,一旦你添加了这些接口和任务,让我们确保我们在项目的构建器管道中配置它们:

  1. builder.Services.AddTransient<ITokenService, TokenService>();
  2. builder.Services.AddTransient<IUserService, UserService>();
  3. builder.Services.AddTransient<ITaskService, TaskService>();

控制器

现在是API的最后一部分,即构建用户访问后端资源的端点:

首先,我们将创建一个新的Controller来继承ControllerBase和在它内部,我们将有一个小的方法和属性来检索登录UserId,无论何时提供访问令牌,都来自基于JWT的访问令牌声明:

所以让我们添加一个API Controller,如下所示:

BaseApiController

  1. using Microsoft.AspNetCore.Mvc;
  2. using System.Security.Claims;
  3. namespace TasksApi.Controllers
  4. {
  5. public class BaseApiController : ControllerBase
  6. {
  7. protected int UserID => int.Parse(FindClaim(ClaimTypes.NameIdentifier));
  8. private string FindClaim(string claimName)
  9. {
  10. var claimsIdentity = HttpContext.User.Identity as ClaimsIdentity;
  11. var claim = claimsIdentity.FindFirst(claimName);
  12. if (claim == null)
  13. {
  14. return null;
  15. }
  16. return claim.Value;
  17. }
  18. }
  19. }

现在我们可以创建将从BaseApiController继承的控制器。

UsersController

让我们从UsersController开始,它将包括四个方法:loginlogoutsignuprefresh访问令牌:

  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Mvc;
  3. using TasksApi.Interfaces;
  4. using TasksApi.Requests;
  5. using TasksApi.Responses;
  6. namespace TasksApi.Controllers
  7. {
  8. [Route("api/[controller]")]
  9. [ApiController]
  10. public class UsersController : BaseApiController
  11. {
  12. private readonly IUserService userService;
  13. private readonly ITokenService tokenService;
  14. public UsersController(IUserService userService, ITokenService tokenService)
  15. {
  16. this.userService = userService;
  17. this.tokenService = tokenService;
  18. }
  19. [HttpPost]
  20. [Route("login")]
  21. public async Task<IActionResult> Login(LoginRequest loginRequest)
  22. {
  23. if (loginRequest == null || string.IsNullOrEmpty(loginRequest.Email) ||
  24. string.IsNullOrEmpty(loginRequest.Password))
  25. {
  26. return BadRequest(new TokenResponse
  27. {
  28. Error = "Missing login details",
  29. ErrorCode = "L01"
  30. });
  31. }
  32. var loginResponse = await userService.LoginAsync(loginRequest);
  33. if (!loginResponse.Success)
  34. {
  35. return Unauthorized(new
  36. {
  37. loginResponse.ErrorCode,
  38. loginResponse.Error
  39. });
  40. }
  41. return Ok(loginResponse);
  42. }
  43. [HttpPost]
  44. [Route("refresh_token")]
  45. public async Task<IActionResult> RefreshToken(RefreshTokenRequest refreshTokenRequest)
  46. {
  47. if (refreshTokenRequest == null || string.IsNullOrEmpty
  48. (refreshTokenRequest.RefreshToken) || refreshTokenRequest.UserId == 0)
  49. {
  50. return BadRequest(new TokenResponse
  51. {
  52. Error = "Missing refresh token details",
  53. ErrorCode = "R01"
  54. });
  55. }
  56. var validateRefreshTokenResponse =
  57. await tokenService.ValidateRefreshTokenAsync(refreshTokenRequest);
  58. if (!validateRefreshTokenResponse.Success)
  59. {
  60. return UnprocessableEntity(validateRefreshTokenResponse);
  61. }
  62. var tokenResponse = await tokenService.GenerateTokensAsync
  63. (validateRefreshTokenResponse.UserId);
  64. return Ok(new { AccessToken = tokenResponse.Item1,
  65. Refreshtoken = tokenResponse.Item2 });
  66. }
  67. [HttpPost]
  68. [Route("signup")]
  69. public async Task<IActionResult> Signup(SignupRequest signupRequest)
  70. {
  71. if (!ModelState.IsValid)
  72. {
  73. var errors = ModelState.Values.SelectMany
  74. (x => x.Errors.Select(c => c.ErrorMessage)).ToList();
  75. if (errors.Any())
  76. {
  77. return BadRequest(new TokenResponse
  78. {
  79. Error = $"{string.Join(",", errors)}",
  80. ErrorCode = "S01"
  81. });
  82. }
  83. }
  84. var signupResponse = await userService.SignupAsync(signupRequest);
  85. if (!signupResponse.Success)
  86. {
  87. return UnprocessableEntity(signupResponse);
  88. }
  89. return Ok(signupResponse.Email);
  90. }
  91. [Authorize]
  92. [HttpPost]
  93. [Route("logout")]
  94. public async Task<IActionResult> Logout()
  95. {
  96. var logout = await userService.LogoutAsync(UserID);
  97. if (!logout.Success)
  98. {
  99. return UnprocessableEntity(logout);
  100. }
  101. return Ok();
  102. }
  103. }
  104. }

注意上面只有注销端点有Authorize装饰,这是因为我们知道用户只要登录就可以注销,这意味着他有一个有效的访问令牌和刷新令牌。

TasksController

这包括允许用户执行任务相关操作的所有端点,例如获取所有用户的任务、保存和删除该用户的任务。

  1. using Microsoft.AspNetCore.Authorization;
  2. using Microsoft.AspNetCore.Mvc;
  3. using TasksApi.Interfaces;
  4. using TasksApi.Requests;
  5. using TasksApi.Responses;
  6. namespace TasksApi.Controllers
  7. {
  8. [Authorize]
  9. [Route("api/[controller]")]
  10. [ApiController]
  11. public class TasksController : BaseApiController
  12. {
  13. private readonly ITaskService taskService;
  14. public TasksController(ITaskService taskService)
  15. {
  16. this.taskService = taskService;
  17. }
  18. [HttpGet]
  19. public async Task<IActionResult> Get()
  20. {
  21. var getTasksResponse = await taskService.GetTasks(UserID);
  22. if (!getTasksResponse.Success)
  23. {
  24. return UnprocessableEntity(getTasksResponse);
  25. }
  26. var tasksResponse = getTasksResponse.Tasks.ConvertAll(o =>
  27. new TaskResponse { Id = o.Id, IsCompleted = o.IsCompleted,
  28. Name = o.Name, Ts = o.Ts });
  29. return Ok(tasksResponse);
  30. }
  31. [HttpPost]
  32. public async Task<IActionResult> Post(TaskRequest taskRequest)
  33. {
  34. var task = new Task { IsCompleted = taskRequest.IsCompleted,
  35. Ts = taskRequest.Ts, Name = taskRequest.Name, UserId = UserID };
  36. var saveTaskResponse = await taskService.SaveTask(task);
  37. if (!saveTaskResponse.Success)
  38. {
  39. return UnprocessableEntity(saveTaskResponse);
  40. }
  41. var taskResponse = new TaskResponse { Id = saveTaskResponse.Task.Id,
  42. IsCompleted = saveTaskResponse.Task.IsCompleted,
  43. Name = saveTaskResponse.Task.Name, Ts = saveTaskResponse.Task.Ts };
  44. return Ok(taskResponse);
  45. }
  46. [HttpDelete("{id}")]
  47. public async Task<IActionResult> Delete(int id)
  48. {
  49. var deleteTaskResponse = await taskService.DeleteTask(id, UserID);
  50. if (!deleteTaskResponse.Success)
  51. {
  52. return UnprocessableEntity(deleteTaskResponse);
  53. }
  54. return Ok(deleteTaskResponse.TaskId);
  55. }
  56. }
  57. }

请注意,该[Authorize]属性正在装饰整体Controller,因为所有这些操作都需要具有有效访问令牌的经过身份验证的用户。

现在我们完成了开发部分。按F5并检查浏览器是否为你的UI显示Swagger API

Postman上进行测试

现在是测试我们整个工作的QA部分,以确保一切正常并符合要求。

当然,请确保您安装并打开了最新版本的Postman

让我们创建一个新集合并将其命名为Tasks Api

我们需要测试的第一件事是登录端点,因为我们已经在数据库中插入了一些测试用户(包括在教程开头的脚本部分中)。

让我们尝试使电子邮件无效并查看结果:

现在让我们测试该signup 方法:

看一下数据库User表:

注意第3条记录,密码从未以纯格式保存,并且随机盐与它相关联。

访问令牌的持续时间通常很短,为1015分钟,一旦过期,您必须使用刷新令牌静默刷新访问令牌,其持续时间要长得多,例如10天或3周,并且这些令牌是在时间上滑动的,所以每当你想刷新和访问令牌时,你可以使用下面的端点来生成一对新的令牌。

refresh_token端点

现在让我们测试刷新令牌端点。在通过任何授权的API调用过期后,您将需要此端点来刷新用户的访问令牌,如下所示:

您将收到401响应,因为访问令牌不再有效,您必须使用第一次登录时拥有的刷新令牌请求新的访问令牌。

让我们尝试刷新令牌:

如果我们尝试刷新之前使用的同一个令牌,它不会起作用,只是因为刷新令牌触发同时生成新的访问令牌和新的刷新令牌,所以之前的刷新令牌将失效(从数据库上的RefreshToken表中删除)。

现在让我们注销用户:

恶意或已注销的用户

现在让我们试试这个场景,一个有效用户退出系统,但顺便说一下,一个恶意用户已经获得了该用户的刷新令牌(以某种方式),并尝试刷新该用户的令牌,以便他可以获得未经授权的访问,我们的API将通过为恶意用户返回以下响应来保护我们的有效用户。

这样,恶意用户就无法访问有效用户的数据。

现在让我们为用户执行获取任务

让我们尝试添加一个新任务

现在让我们删除一个任务

总结

今天,我们学习了如何使用SQL Server Express从数据库开始构建一个小型简单的任务管理系统,将其与.NET 6中的ASP.NET Core Web APIVisual Studio 2022中的C# 10连接。我们使用EF映射数据库Core(在强大的EF Core Power Tools 的慷慨帮助下),然后使用JWTBearer Nuget包,我们设法在API项目上设置和实施基于JWT的身份验证,同时应用刷新令牌以使其更加实用用户无需每1015分钟重新执行一次登录过程即可获得API的身份验证和授权。

您可以在我的GitHub帐户中找到本教程的源代码。

https://www.codeproject.com/Articles/5325297/Apply-JWT-Access-Tokens-and-Refresh-Tokens-in-ASP

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/539688
推荐阅读
相关标签
  

闽ICP备14008679号