原文地址:https://www.jeremyjone.com/800/,转载请注明。
开始之前
更多内容,可以看我的文档:.NET 学习之路-数据的持久化
正文开始
前面只是一个最简单的基础使用方案,虽然已经实现了认证与授权,但是明显并不能满足生产需求,下面就按不同需求进行配置。
上面的例子中,所有数据都在内存中,并不能持久化。如果要数据持久化,上数据库是必然的。
创建使用数据库的项目
-
通过命令可以快速创建一个带有模板的项目:
dotnet new is4ef
-
下载 示例代码 可以获取完整的配置内容。
-
也可以创建空项目后按照下面内容自行配置。
配置数据库服务
使用上面命令创建的项目会包含比较完整的内容,下面对项目稍作修改。
添加数据库相关依赖
IdentityServer4.AspNetIdentity(4.1.2)
IdentityServer4.EntityFramework(4.0.0)
Microsoft.EntityFrameworkCore.Tools(3.1.5)
Microsoft.AspNetCore.Identity.EntityFrameworkCore(3.1.5)
Pomelo.EntityFrameworkCore.MySql(3.1.1)
注意:截至 2021.3.20,Pomelo.EntityFrameworkCore.MySql 不支持 Net5(想尝鲜可以使用 alpha-5 版本),项目是 net core 3.1 的,对应的 Pomelo.EntityFrameworkCore.MySql 使用的是 3.1.1 版本,对应的 Microsoft.EntityFrameworkCore.Tools 也应该是 3.x 版本。
本配置为 MySQL,如果使用其他数据库,请自行下载。
添加数据库连接字符串
在 appsettings.json
中添加如下内容:
{
"ConnectionStrings": {
// 使用命令创建的项目自带默认字符串,连接 SQLite 的
"DefaultConnection": "Data Source=IdentityServer.db;",
// 添加 MySQL 的连接字符串
"MySQL": "server=192.168.1.126;userid=jeremyjone;pwd=123456;port=3306;database=ids-test"
}
}
注册数据库的相关服务
在 Startup.cs
的配置服务中添加如下内容:
添加数据库上下文
var connectionMySql = Configuration["ConnectionStrings:MySQL"];
if (string.IsNullOrWhiteSpace(connectionMySql))
{
throw new Exception("数据库配置异常,请检查 appsettings.json");
}
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(connectionMySql));
配置身份参数
services.AddIdentity<ApplicationUser, ApplicationRole>()
// 添加实体库
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
配置 IS4 为数据库模式
空项目不需要添加被注释掉的内容。如果使用命令创建的项目,会默认使用 SQLite 进行配置,按中文注释稍作修改即可。
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var builder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
// see https://identityserver4.readthedocs.io/en/latest/topics/resources.html
options.EmitStaticAudienceClaim = true;
})
// 注释掉测试用户,使用数据库的内容
//.AddTestUsers(TestUsers.Users)
// 配置 IS4 使用哪种用户模型
.AddAspNetIdentity<ApplicationUser>()
// this adds the config data from DB (clients, resources, CORS)
.AddConfigurationStore(options =>
{
//options.ConfigureDbContext = builder => builder.UseSqlite(connectionString);
// 使用 MySQL
options.ConfigureDbContext = b =>
b.UseMySql(connectionMySQL, sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
//options.ConfigureDbContext = builder => builder.UseSqlite(connectionString);
// 使用 MySQL
options.ConfigureDbContext = b =>
b.UseMySql(connectionMySQL, sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
});
// not recommended for production - you need to store your key material somewhere secure
builder.AddDeveloperSigningCredential();
不要忘记在中间件注册使用 IS4
app.UseRouting();
// 注册使用 IS4 服务。它需要在 *路由* 之后,*授权* 之前。
app.UseIdentityServer();
app.UseAuthorization();
创建数据模型
上面配置了自定义的 ApplicationDbContext
和 ApplicationUser
,因为通常用户的内容我们需要自定义,如果完全不用自定义的话,那么直接使用原型(IdentityUser)即可。
在项目根目录下新建一个 Models
文件夹并创建下面几个模型类:
创建自定义用户模型
// ApplicationUser.cs
public class ApplicationUser : IdentityUser<int>
{
/// <summary>
/// 有效
/// </summary>
public bool Validity {
get; set; } = true;
/// <summary>
/// 昵称
/// </summary>
public string NickName {
get; set; }
/// <summary>
/// 出生日期
/// </summary>
public DateTime BirthDate {
get; set; }
public ICollection<ApplicationUserRole> UserRoles {
get;