首页 > 其他分享 >identity4 系列————用户数据持久化篇[六]

identity4 系列————用户数据持久化篇[六]

时间:2022-08-28 17:11:45浏览次数:81  
标签:Claim 持久 化篇 alice result new bob options identity4

前言

前面的例子已经将各种情形下的例子已经介绍了一遍,那么后面就是用户数据持久化该如何处理了。

正文

例子位置:

https://github.com/IdentityServer/IdentityServer4/tree/main/samples/Quickstarts/6_AspNetIdentity

里面介绍如何将用户数据持久化到数据库。

  1. 配置数据库
services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

然后添加认证服务:

services.AddIdentity<ApplicationUser, IdentityRole>()
			.AddEntityFrameworkStores<ApplicationDbContext>()
			.AddDefaultTokenProviders();

这个就是前面的增加认证服务的一系列东西。

这里可以看下源码:

当然里面还有一些角色管理和用户管理的配置:

然后一些配置和前面的一样:

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;
            })
                .AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddInMemoryClients(Config.Clients)
                .AddAspNetIdentity<ApplicationUser>();

这样其实就可以了。

  1. 初始化数据
public static void EnsureSeedData(string connectionString)
{
	var services = new ServiceCollection();
	services.AddLogging();
	services.AddDbContext<ApplicationDbContext>(options =>
	   options.UseSqlite(connectionString));

	services.AddIdentity<ApplicationUser, IdentityRole>()
		.AddEntityFrameworkStores<ApplicationDbContext>()
		.AddDefaultTokenProviders();

	using (var serviceProvider = services.BuildServiceProvider())
	{
		using (var scope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
		{
			var context = scope.ServiceProvider.GetService<ApplicationDbContext>();
			context.Database.Migrate();

			var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
			var alice = userMgr.FindByNameAsync("alice").Result;
			if (alice == null)
			{
				alice = new ApplicationUser
				{
					UserName = "alice",
					Email = "[email protected]",
					EmailConfirmed = true,
				};
				var result = userMgr.CreateAsync(alice, "Pass123$").Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}

				result = userMgr.AddClaimsAsync(alice, new Claim[]{
					new Claim(JwtClaimTypes.Name, "Alice Smith"),
					new Claim(JwtClaimTypes.GivenName, "Alice"),
					new Claim(JwtClaimTypes.FamilyName, "Smith"),
					new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
				}).Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}
				Log.Debug("alice created");
			}
			else
			{
				Log.Debug("alice already exists");
			}

			var bob = userMgr.FindByNameAsync("bob").Result;
			if (bob == null)
			{
				bob = new ApplicationUser
				{
					UserName = "bob",
					Email = "[email protected]",
					EmailConfirmed = true
				};
				var result = userMgr.CreateAsync(bob, "Pass123$").Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}

				result = userMgr.AddClaimsAsync(bob, new Claim[]{
					new Claim(JwtClaimTypes.Name, "Bob Smith"),
					new Claim(JwtClaimTypes.GivenName, "Bob"),
					new Claim(JwtClaimTypes.FamilyName, "Smith"),
					new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
					new Claim("location", "somewhere")
				}).Result;
				if (!result.Succeeded)
				{
					throw new Exception(result.Errors.First().Description);
				}
				Log.Debug("bob created");
			}
			else
			{
				Log.Debug("bob already exists");
			}
		}
	}
}

里面就不多介绍了,就是如果不存在就数据。

下一节介绍各个表的作用。

标签:Claim,持久,化篇,alice,result,new,bob,options,identity4
From: https://www.cnblogs.com/aoximin/p/16632368.html

相关文章

  • identity4 系列————持久化配置篇[五]
    前言上面已经介绍了3个例子了,并且介绍了如何去使用identity。但是在前面的例子中,我们使用的都是在内存中操作,那么正式上线可能需要持久到数据库中。这里值得说明的是,并......
  • identity4 系列————纯js客户端案例篇[四]
    前言前面已经解释了两个案例了,通信原理其实已经很清楚了,那么纯js客户端是怎么处理的呢?正文直接贴例子哈。https://github.com/IdentityServer/IdentityServer4/tree/ma......
  • 【MySQL】MySQL8持久化系统变量
    set命令可以用于将某些全局系统变量持久化到数据目录中的mysqld-auto.cnf文件中,以影响后续启动的服务器操作。resetpersist从mysqld-auto.cnf中删除持久设置。在运行时持......
  • identity4 系列————案例篇[三]
    前言前文介绍了identity的用法,同时介绍了什么是identitySourece、apiSource、client这几个概念,和具体案例,那么下面继续介绍案例了。正文这里用官网的案例,因为学习一门......
  • K8S(kubernetes)基于nfs实现持久化(PV+PVC)
     k8s集群情况:[21:56:22root@k8s-master~]#kubectlgetnodesNAMESTATUSROLESAGEVERSIONk8s-masterReadymaster10dv1.......
  • Redis_持久化
    Redis_持久化持久化:redis是一个内存数据库,当redis服务器重启,获取电脑重启,数据会丢失,我们才可以键redis内存中的数据持久化保存到硬盘的文件中redis持久化机构:......
  • identity4 系列————案例篇[三]
    前言前文介绍了identity的用法,同时介绍了什么是identitySourece、apiSource、client这几个概念,和具体案例,那么下面继续介绍案例了。正文这里用官网的案例,因为学习一门......
  • k8s对接Ceph实现持久化存储(16)
    一、Ceph简介官网:https://ceph.com/en/https://docs.ceph.com/en/latest/start/intro/ceph是一种开源的分布式的存储系统包含以下几种存储类型:块存储(rbd),对象存储......
  • redis持久化
    redis如何实现数据不丢失:为了保证Redis数据不丢失,要把数据从内存存储到磁盘上,这就是Redis的数据持久化。Redis数据持久化有三种方式:1)AOF日志(AppendOnlyFile,文件追加方......
  • java帝国的诞生——一场旷日持久的战争
    一、C&C++聊到java的诞生,就不得不谈谈C语言和C++。C语言诞生于1972年,而java则是在1995年才出现,这中间时间跨度还是蛮大的。C语言在java出现之前已经统治了二十多年了。......