• 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 = "AliceSmith@email.com",
    					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 = "BobSmith@email.com",
    					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");
    			}
    		}
    	}
    }
    

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

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

  • 相关阅读:
    Postfix常用命令和邮件队列管理(queue)
    window7下面rabbitMQ安装配置过程详解
    RabbitMQ系列之消息确认机制
    全文检索:sphinx elasticsearch xunsearch 比较
    用SQL命令查看Mysql数据库大小
    部署Percona监控和管理--- PMM Server
    什么是MTU?为什么MTU值普遍都是1500?
    Mysql删除数据后,磁盘空间未释放的解决办法
    数据库索引
    visual studio 容器工具首次加载太慢 vsdbgvs2017u5 exists, deleting 的解决方案
  • 原文地址:https://www.cnblogs.com/aoximin/p/16632368.html
Copyright © 2020-2023  润新知