Microsoft.AspNetCore.Identity

前言

用户模块几乎是每个系统必备的基础功能,如果每次开发一个新项目时都要做个用户模块,确实非常无聊。好在asp.net core给我们提供了Identity,使用起来也是比较方便,如果对用户这块需求不是非常个性化的话,identity是一个不错的选择。

ASP.NET Core Identity:

  • 是一个 API,它支持用户 登录功能(UI界面) 。

  • 管理用户、密码、配置文件数据、角色、声明、令牌、电子邮件确认等。

Web API中集成Identity

identity是支持UI界面的,如果不是前后端分离项目,可以直接集成identity UI模块,因为我这里使用Web API,就忽略掉identity UI部分。

安装相关包

下面介绍以最小化方式引入identity。

首先创建一个Web API空项目,NuGet安装identity、efcore、jwt相关包,数据库我这里就使用mysql:

 <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="7.0.10" />
 <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" />
 <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="7.0.0" />
 <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.10">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
 </PackageReference>

自定义User,Context

创建自己的User实体,继承IdentityUserIdentityUser中已经有一些基础字段,你可以在你的AppUser中额外定义一些自己需要的字段,比如Description

public class AppUser : IdentityUser
{
    [Required] 
    [StringLength(128)] 
    public string Description{ get; set; }
}

 

创建自己的DbContext,继承IdentityDbContext<>,泛型传入自己的AppUser

 public class AppDbContext : IdentityDbContext<AppUser, AppRole, Guid>
    {
        public AppDbContext(DbContextOptions<AppDbContext> options)
            : base(options)
        {
        }protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity<AppUser>(b => { b.ToTable("AppUsers"); });

            builder.Entity<AppRole>(b => { b.ToTable("AppUserRoles"); });

            builder.Entity<IdentityUserClaim<Guid>>(b => { b.ToTable("AppUserClaims"); });

            builder.Entity<IdentityUserLogin<Guid>>(b => { b.ToTable("AppUserLogins"); });

            builder.Entity<IdentityUserToken<Guid>>(b => { b.ToTable("AppUserTokens"); });

            builder.Entity<IdentityRole<Guid>>(b => { b.ToTable("AppRoles"); });

            builder.Entity<IdentityRoleClaim<Guid>>(b => { b.ToTable("AppRoleClaims"); });
        }
    }

 

 

注入服务服务:

            
            // 注册数据库DB
            var connectionString = configuration.GetConnectionString("DefaultConnection");
            services.AddDbContext<AppDbContext>(options =>
                options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString)));
            // 注册Identity
            //services.AddIdentity<AppUser, AppRole>(options =>
            //{
            //    // 配置密码规则
            //    options.Password.RequireDigit = true;
            //    options.Password.RequireLowercase = false;
            //    options.Password.RequireUppercase = false;
            //    options.Password.RequireNonAlphanumeric = false;
            //}).AddEntityFrameworkStores<AppDbContext>();
            services.AddIdentityCore<AppUser>(options =>
            {
                // 配置密码规则
                options.Password.RequireDigit = true;
                options.Password.RequireLowercase = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireNonAlphanumeric = false;
            }).AddEntityFrameworkStores<AppDbContext>();       

appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Port=3306;Database=YaDea;Uid=ya;Pwd=123456;"
  }

这样一个最简单的自定义配置就完成了。

数据库迁移

使用dotnet ef命令迁移:

dotnet ef migrations add init -c AppDbContext
dotnet ef database update -c AppDbContext

 JWT配置 

首先NuGet安装包:

<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.10" />

appsettings.json中添加jwt配置:

"JwtSettingOptions": {
    "SecurityKey": "qP1yR9qH2xS0vW2lA3gI4nF0zA7fA3hB",
    "ExpiresIn": "00:10:00"
  }

注册jwt服务

 // 注册JWT配置
            var configurationSectionJwtSettingOptions = configuration.GetSection(nameof(JwtSettingOptions));
            services.Configure<JwtSettingOptions>(configurationSectionJwtSettingOptions);
            var jwtSettings = configurationSectionJwtSettingOptions.Get<JwtSettingOptions>();

            // 注册身份认证
            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        ValidateAudience = false,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSettings.SecurityKey)),
                        ClockSkew = TimeSpan.Zero,
                    };
                });

            // Add services to the container.
            services.AddAuthorization();

最后别忘了UseAuthentication

            // 身份认证
            app.UseAuthentication();

            // 授权
            app.UseAuthorization();

结构搭建

下面把项目基本结构搭建好,做好接口,后面实现:

以下是各个类的定义:

// 用户注册请求参数
public class RegisterRequest
{
    public string UserName { get; set; }
    
    public string Password { get; set; }
    
    public string Address { get; set; }
}
// 用户登录请求参数
public class LoginRequest
{
    public string UserName { get; set; }
    
    public string Password { get; set; }
}
// 注册 登录 成功后返回 token
public class TokenResponse
{
    [JsonPropertyName("access_token")] 
    public string AccessToken { get; set; }
    
    [JsonPropertyName("token_type")] 
    public string TokenType { get; set; }
}
// 登录 注册 失败时返回错误信息
public class FailedResponse
{
    public IEnumerable<string> Errors { get; set; }
}
// IUserService 接口
public interface IUserService
{
    Task<TokenResult> RegisterAsync(string username, string password, string address);
    
    Task<TokenResult> LoginAsync(string username, string password);
}
// UserService 实现
public class UserService : IUserService
{
    public Task<TokenResult> RegisterAsync(string username, string password, string address)
    {
        throw new System.NotImplementedException();
    }
    public Task<TokenResult> LoginAsync(string username, string password)
    {
        throw new System.NotImplementedException();
    }
}
// TokenResult 定义
public class TokenResult
{
    public bool Success => Errors == null || !Errors.Any();
    public IEnumerable<string> Errors { get; set; }
    
    public string AccessToken { get; set; }
    public string TokenType { get; set; }
}

最后是UserController

 [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            _userService = userService;
        }

        [HttpPost("Register")]
        [ProducesResponseType(typeof(TokenResponse), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(FailedResponse), StatusCodes.Status400BadRequest)]
        public async Task<IActionResult> Register(RegisterRequest request)
        {
            var result = await _userService.RegisterAsync(request.UserName, request.Password, request.Address);
            if (!result.Success)
            {
                return BadRequest(new FailedResponse()
                {
                    Errors = result.Errors
                });
            }

            return Ok(new TokenResponse
            {
                AccessToken = result.AccessToken,
                TokenType = result.TokenType,
                ExpiresIn = result.ExpiresIn,
                RefreshToken = result.RefreshToken
            });
        }

        [HttpPost("Login")]
        [ProducesResponseType(typeof(TokenResponse), StatusCodes.Status200OK)]
        [ProducesResponseType(typeof(FailedResponse), StatusCodes.Status401Unauthorized)]
        public async Task<IActionResult> Login(LoginRequest request)
        {
            var result = await _userService.LoginAsync(request.UserName, request.Password);
            if (!result.Success)
            {
                return Unauthorized(new FailedResponse()
                {
                    Errors = result.Errors
                });
            }

            return Ok(new TokenResponse
            {
                AccessToken = result.AccessToken,
                TokenType = result.TokenType,
                ExpiresIn = result.ExpiresIn,
                RefreshToken = result.RefreshToken
            });
        }
    }

service实现

上面已经做好了基本的结构,接下来就是实现UserService中的RegisterAsyncLoginAsync方法了。这里主要用到identity中的UserManagerUserManager封装了很多用户操作的现成方法。

UserService中先做一个私有方法,根据user创建jwt token;用户注册,登录成功后调用此方法得到token返回即可:

private TokenResult GenerateJwtToken(AppUser user)
{
    var key = Encoding.ASCII.GetBytes(_jwtSettings.SecurityKey);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[]
        {
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
            new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString())
        }),
        IssuedAt = DateTime.UtcNow,
        NotBefore = DateTime.UtcNow,
        Expires = DateTime.UtcNow.Add(_jwtSettings.ExpiresIn),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
            SecurityAlgorithms.HmacSha256Signature)
    };
    var jwtTokenHandler = new JwtSecurityTokenHandler();
    var securityToken = jwtTokenHandler.CreateToken(tokenDescriptor);
    var token = jwtTokenHandler.WriteToken(securityToken);
    return new TokenResult()
    {
        AccessToken = token,
        TokenType = "Bearer"
    };
}

注册方法实现:

public async Task<TokenResult> RegisterAsync(string username, string password, string address)
{
    var existingUser = await _userManager.FindByNameAsync(username);
    if (existingUser != null)
    {
        return new TokenResult()
        {
            Errors = new[] {"user already exists!"}, //用户已存在
        };
    }
    var newUser = new AppUser() {UserName = username, Address = address};
    var isCreated = await _userManager.CreateAsync(newUser, password);
    if (!isCreated.Succeeded)
    {
        return new TokenResult()
        {
            Errors = isCreated.Errors.Select(p => p.Description)
        };
    }
    return GenerateJwtToken(newUser);
}

登录方法实现:

public async Task<TokenResult> LoginAsync(string username, string password)
{
    var existingUser = await _userManager.FindByNameAsync(username);
    if (existingUser == null)
    {
        return new TokenResult()
        {
            Errors = new[] {"user does not exist!"}, //用户不存在
        };
    }
    var isCorrect = await _userManager.CheckPasswordAsync(existingUser, password);
    if (!isCorrect)
    {
        return new TokenResult()
        {
            Errors = new[] {"wrong user name or password!"}, //用户名或密码错误
        };
    }
    return GenerateJwtToken(existingUser);
}

最后,别忘了注册UserService

services.AddScoped<IUserService, UserService>();

refresh token配置

开始之前先说明一下为什么需要refresh token。

虽然jwt token有很多优点,但是它的缺点也是非常明显。由于jwt无状态的特性,所以jwt一旦颁发,基本上就不可控了,在过期时间内一直有效。有些场景下我们是希望能控制token失效的,比如用户的重要数据被修改时(密码,角色,权限,等等),我们希望用户重新获取token,甚至重新登录。

那么refresh token就可以很好的弥补jwt的缺陷。虽然refresh token也无法直接控制jwt失效,但是在refresh token机制下,我们可以把token的有效期设置的短一些,比如30分钟,而refresh token的有效期可以很长;因为refresh token会持久化到数据库中,它是完全可控的。

很多人纠结的jwt滑动刷新,无感刷新,在refresh token机制下,都不是问题。

成refresh_token

改造一下上一篇的代码,首先refresh token需要持久化到数据库中,定义实体:

public class RefreshToken
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(128)]
    public string JwtId { get; set; }

    [Required]
    [StringLength(256)]
    public string Token { get; set; }

    /// <summary>
    /// 是否使用,一个RefreshToken只能使用一次
    /// </summary>
    [Required]
    public bool Used { get; set; }

    /// <summary>
    /// 是否失效。修改用户重要信息时可将此字段更新为true,使用户重新登录
    /// </summary>
    [Required]
    public bool Invalidated { get; set; }

    [Required]
    public DateTime CreationTime { get; set; }

    [Required]
    public DateTime ExpiryTime { get; set; }

    [Required]
    public int UserId { get; set; }

    [Required]
    [ForeignKey(nameof(UserId))]
    public AppUser User { get; set; }
}

加入到DbContext:

public class AppDbContext : IdentityDbContext<AppUser, IdentityRole<int>, int>
{
    public DbSet<RefreshToken> RefreshTokens { get; set; }

    public AppDbContext(DbContextOptions<AppDbContext> options)
        : base(options)
    {
    }
    
    // 省略......
}

ef迁移:

dotnet ef migrations add AppDbContext_Added_RefreshToken

dotnet ef database update

登录注册返回token时,也要把RefreshToken和ExpiresIn有效时间一起返回:

public class TokenResult
{
    public bool Success => Errors == null || !Errors.Any();
    public IEnumerable<string> Errors { get; set; }

    
    public string AccessToken { get; set; }

    public string TokenType { get; set; }

    public int ExpiresIn { get; set; }   // add
    
    public string RefreshToken { get; set; }  // add
}
public class TokenResponse
{
    [JsonPropertyName("access_token")] 
    public string AccessToken { get; set; }

    [JsonPropertyName("token_type")] 
    public string TokenType { get; set; }

    [JsonPropertyName("expires_in")]
    public int ExpiresIn { get; set; }  // add

    [JsonPropertyName("refresh_token")]
    public string RefreshToken { get; set; } // add
}

修改UserService创建token方法:

 

private async Task<TokenResult> GenerateJwtToken(AppUser user)
{
    var key = Encoding.ASCII.GetBytes(_jwtSettings.SecurityKey);

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[]
        {
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")),
            new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString())
        }),
        IssuedAt = DateTime.UtcNow,
        NotBefore = DateTime.UtcNow,
        Expires = DateTime.UtcNow.Add(_jwtSettings.ExpiresIn),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
            SecurityAlgorithms.HmacSha256Signature)
    };

    var jwtTokenHandler = new JwtSecurityTokenHandler();
    var securityToken = jwtTokenHandler.CreateToken(tokenDescriptor);
    var token = jwtTokenHandler.WriteToken(securityToken);

    var refreshToken = new RefreshToken()
    {
        JwtId = securityToken.Id,
        UserId = user.Id,
        CreationTime = DateTime.UtcNow,
        ExpiryTime = DateTime.UtcNow.AddMonths(6),
        Token = GenerateRandomNumber()
    };

    await _appDbContext.RefreshTokens.AddAsync(refreshToken);
    await _appDbContext.SaveChangesAsync();

    return new TokenResult()
    {
        AccessToken = token,
        TokenType = "Bearer",
        RefreshToken = refreshToken.Token,
        ExpiresIn = (int)_jwtSettings.ExpiresIn.TotalSeconds,
    };
}
private string GenerateRandomNumber(int len = 32)
{
    var randomNumber = new byte[len];
    using var rng = RandomNumberGenerator.Create();
    rng.GetBytes(randomNumber);
    return Convert.ToBase64String(randomNumber);
}

使用refresh_token获取token

// RefreshToken 请求参数
public class RefreshTokenRequest
{
    [JsonPropertyName("access_token")]
    public string AccessToken { get; set; }
    
    [JsonPropertyName("refresh_token")]
    public string RefreshToken { get; set; }
}
public interface IUserService
{
    // 省略......
    
    Task<TokenResult> RefreshTokenAsync(string token, string refreshToken); // add
}

RefreshTokenAsync实现:

public async Task<TokenResult> RefreshTokenAsync(string token, string refreshToken)
{
    var claimsPrincipal = GetClaimsPrincipalByToken(token);
    if (claimsPrincipal == null)
    {
        // 无效的token...
        return new TokenResult()
        {
            Errors = new[] { "1: Invalid request!" },
        };
    }

    var expiryDateUnix =
        long.Parse(claimsPrincipal.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Exp).Value);
    var expiryDateTimeUtc = UnixTimeStampToDateTime(expiryDateUnix);
    if (expiryDateTimeUtc > DateTime.UtcNow)
    {
        // token未过期...
        return new TokenResult()
        {
            Errors = new[] { "2: Invalid request!" },
        };
    }

    var jti = claimsPrincipal.Claims.Single(x => x.Type == JwtRegisteredClaimNames.Jti).Value;

    var storedRefreshToken =
        await _appDbContext.RefreshTokens.SingleOrDefaultAsync(x => x.Token == refreshToken);
    if (storedRefreshToken == null)
    {
        // 无效的refresh_token...
        return new TokenResult()
        {
            Errors = new[] { "3: Invalid request!" },
        };
    }
    
    if (storedRefreshToken.ExpiryTime < DateTime.UtcNow)
    {
        // refresh_token已过期...
        return new TokenResult()
        {
            Errors = new[] { "4: Invalid request!" },
        };
    }
    
    if (storedRefreshToken.Invalidated)
    {
        // refresh_token已失效...
        return new TokenResult()
        {
            Errors = new[] { "5: Invalid request!" },
        };
    }
    
    if (storedRefreshToken.Used)
    {
        // refresh_token已使用...
        return new TokenResult()
        {
            Errors = new[] { "6: Invalid request!" },
        };
    }
    
    if (storedRefreshToken.JwtId != jti)
    {
        // refresh_token与此token不匹配...
        return new TokenResult()
        {
            Errors = new[] { "7: Invalid request!" },
        };
    }
    
    storedRefreshToken.Used = true;
    //_userDbContext.RefreshTokens.Update(storedRefreshToken);
    await _appDbContext.SaveChangesAsync();
    
    var dbUser = await _userManager.FindByIdAsync(storedRefreshToken.UserId.ToString());
    return await GenerateJwtToken(dbUser);
}

解析token,注意这里的tokenValidationParameters,这个参数和Startup中设置的tokenValidationParameters唯一的区别是ValidateLifetime = false,不验证过期时间。

private ClaimsPrincipal GetClaimsPrincipalByToken(string token)
{
    try
    {
        var tokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = false,
            ValidateAudience = false,
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_jwtSettings.SecurityKey)),
            ClockSkew = TimeSpan.Zero,
            ValidateLifetime = false // 不验证过期时间!!!
        };
        
        var jwtTokenHandler = new JwtSecurityTokenHandler();
        
        var claimsPrincipal =
            jwtTokenHandler.ValidateToken(token, tokenValidationParameters, out var validatedToken);
        
        var validatedSecurityAlgorithm = validatedToken is JwtSecurityToken jwtSecurityToken
                                         && jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256,
                                             StringComparison.InvariantCultureIgnoreCase);
        
        return validatedSecurityAlgorithm ? claimsPrincipal : null;
    }
    catch
    {
        return null;
    }
}

最后是UserController:

[HttpPost("RefreshToken")]
public async Task<IActionResult> RefreshToken(RefreshTokenRequest request)
{
    var result = await _userService.RefreshTokenAsync(request.AccessToken, request.RefreshToken);
    if (!result.Success)
    {
        return Unauthorized(new FailedResponse()
        {
            Errors = result.Errors
        });
    }
    
    return Ok(new TokenResponse
    {
        AccessToken = result.AccessToken,
        TokenType = result.TokenType,
        ExpiresIn = result.ExpiresIn,
        RefreshToken = result.RefreshToken
    });
}

        [HttpGet("Test")]
        [Authorize]
        public string Get()
        {
            return "身份认证成功返回数据";
        }

测试 

注册

 

登录

 

刷新Token

请求授权接口

 总结一下

上面的代码看似很多,其实完成的功能非常简单;就是在用户获取token时,后台生成一个与之对应的refresh token一并返回,同时将refresh token保存到数据库中;refresh token的存在就是为了当token过期时,能免登录刷新一次token。(refresh token只能使用一次,用户重要数据比如密码修改时,可以将refresh token置为失效,使用户重新登录)。代码已上传至github )

 
posted @ 2023-08-24 17:44  刘小吉  阅读(271)  评论(0编辑  收藏  举报