• 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");
    			}
    		}
    	}
    }
    

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

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

  • 相关阅读:
    魅力惠_百度百科
    新奢侈主义_百度百科
    FastSocket学习笔记~再说客户端与服务端的组成
    在线支付文章索引(支付宝_微信_银联)
    微信JSApi支付~微信支付代理模式的实现(原创)
    爱上MVC~ajax调用分部视图session超时页面跳转问题
    C#~异步编程再续~await与async引起的w3wp.exe崩溃-问题友好的解决
    poj-3895-Cycles of Lanes 简单DFS
    How to search a table in a store proc and open the store proc
    Github-Client(ANDROID)开源之旅(四) ------ 简介Roboguice
  • 原文地址:https://www.cnblogs.com/aoximin/p/16632368.html
Copyright © 2020-2023  润新知