forked from udap-tools/udap-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSeedData.Identity.Provider2.cs
232 lines (189 loc) · 8.72 KB
/
SeedData.Identity.Provider2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
Copyright (c) Joseph Shook. All rights reserved.
Authors:
Joseph Shook [email protected]
See LICENSE in the project root for license information.
*/
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Duende.IdentityServer;
using Duende.IdentityServer.EntityFramework.DbContexts;
using Duende.IdentityServer.EntityFramework.Mappers;
using Duende.IdentityServer.EntityFramework.Storage;
using Duende.IdentityServer.Models;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Udap.Model;
using Udap.Server.DbContexts;
using Udap.Server.Entities;
using Udap.Server.Models;
using Udap.Server.Storage.Stores;
using Udap.Server.Stores;
using Udap.Util.Extensions;
using ILogger = Serilog.ILogger;
using Task = System.Threading.Tasks.Task;
namespace UdapDb;
public static class SeedDataIdentityProvider2
{
private static Anchor anchor;
/// <summary>
/// Load some test dat
/// </summary>
/// <param name="connectionString"></param>
/// <param name="certStoreBasePath">Test certs base path</param>
/// <param name="logger"></param>
/// <param name="identityProvider">Load different scopes</param>
public static async Task<int> EnsureSeedData(string connectionString, string certStoreBasePath, ILogger logger)
{
var services = new ServiceCollection();
services.AddLogging(c => c.AddSerilog());
services.AddOperationalDbContext(options =>
{
options.ConfigureDbContext = db => db.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(typeof(Program).Assembly.FullName));
});
services.AddConfigurationDbContext(options =>
{
options.ConfigureDbContext = db => db.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(typeof(Program).Assembly.FullName));
});
services.AddScoped<IUdapClientRegistrationStore, UdapClientRegistrationStore>();
services.AddUdapDbContext(options =>
{
options.UdapDbContext = db => db.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(typeof(Program).Assembly.FullName));
});
await using var serviceProvider = services.BuildServiceProvider();
using var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope();
await serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.MigrateAsync();
var configDbContext = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
await configDbContext.Database.MigrateAsync();
var udapContext = serviceScope.ServiceProvider.GetRequiredService<UdapDbContext>();
await udapContext.Database.MigrateAsync();
var clientRegistrationStore = serviceScope.ServiceProvider.GetRequiredService<IUdapClientRegistrationStore>();
if (!udapContext.Communities.Any(c => c.Name == "udap://Provider2"))
{
var community = new Community { Name = "udap://Provider2" };
community.Enabled = true;
community.Default = true;
udapContext.Communities.Add(community);
await udapContext.SaveChangesAsync();
}
var assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
//
// Anchor localhost_fhirlabs_community2 for Udap.Identity.Provider2
//
var anchorUdapIdentityProvider2 = new X509Certificate2(
Path.Combine(assemblyPath!, certStoreBasePath, "localhost_fhirlabs_community2/caLocalhostCert2.cer"));
if ((await clientRegistrationStore.GetAnchors("udap://Provider2"))
.All(a => a.Thumbprint != anchorUdapIdentityProvider2.Thumbprint))
{
var community = udapContext.Communities.Single(c => c.Name == "udap://Provider2");
anchor = new Anchor
{
BeginDate = anchorUdapIdentityProvider2.NotBefore.ToUniversalTime(),
EndDate = anchorUdapIdentityProvider2.NotAfter.ToUniversalTime(),
Name = anchorUdapIdentityProvider2.Subject,
Community = community,
X509Certificate = anchorUdapIdentityProvider2.ToPemFormat(),
Thumbprint = anchorUdapIdentityProvider2.Thumbprint,
Enabled = true
};
udapContext.Anchors.Add(anchor);
await udapContext.SaveChangesAsync();
}
var intermediateCertProvider2 = new X509Certificate2(
Path.Combine(assemblyPath!, certStoreBasePath,
"localhost_fhirlabs_community2/intermediates/intermediateLocalhostCert2.cer"));
if ((await clientRegistrationStore.GetIntermediateCertificates())
.All(a => a.Thumbprint != intermediateCertProvider2.Thumbprint))
{
var anchorProvider2 = udapContext.Anchors.Single(a => a.Thumbprint == anchorUdapIdentityProvider2.Thumbprint);
//
// Intermediate surefhirlabs_community
//
var x509Certificate2Collection = await clientRegistrationStore.GetIntermediateCertificates();
if (x509Certificate2Collection != null && x509Certificate2Collection.ToList()
.All(r => r.Thumbprint != intermediateCertProvider2.Thumbprint))
{
udapContext.IntermediateCertificates.Add(new Intermediate
{
BeginDate = intermediateCertProvider2.NotBefore.ToUniversalTime(),
EndDate = intermediateCertProvider2.NotAfter.ToUniversalTime(),
Name = intermediateCertProvider2.Subject,
X509Certificate = intermediateCertProvider2.ToPemFormat(),
Thumbprint = intermediateCertProvider2.Thumbprint,
Enabled = true,
Anchor = anchorProvider2
});
await udapContext.SaveChangesAsync();
}
}
/*
* "openid",
"fhirUser",
"email", ????
"profile"
*/
//
// openid
//
if (configDbContext.IdentityResources.All(i => i.Name != IdentityServerConstants.StandardScopes.OpenId))
{
var identityResource = new IdentityResources.OpenId();
configDbContext.IdentityResources.Add(identityResource.ToEntity());
await configDbContext.SaveChangesAsync();
}
//
// fhirUser
//
if (configDbContext.IdentityResources.All(i => i.Name != UdapConstants.StandardScopes.FhirUser))
{
var fhirUserIdentity = new UdapIdentityResources.FhirUser();
configDbContext.IdentityResources.Add(fhirUserIdentity.ToEntity());
await configDbContext.SaveChangesAsync();
}
//
// udap
//
if (configDbContext.ApiScopes.All(i => i.Name != UdapConstants.StandardScopes.Udap))
{
var udapIdentity = new UdapApiScopes.Udap();
configDbContext.ApiScopes.Add(udapIdentity.ToEntity());
await configDbContext.SaveChangesAsync();
}
//
// profile
//
if (configDbContext.IdentityResources.All(i => i.Name != IdentityServerConstants.StandardScopes.Profile))
{
var identityResource = new UdapIdentityResources.Profile();
configDbContext.IdentityResources.Add(identityResource.ToEntity());
await configDbContext.SaveChangesAsync();
}
//
// email
//
if (configDbContext.IdentityResources.All(i => i.Name != IdentityServerConstants.StandardScopes.Email))
{
var identityResource = new IdentityResources.Email();
configDbContext.IdentityResources.Add(identityResource.ToEntity());
await configDbContext.SaveChangesAsync();
}
var sb = new StringBuilder();
sb.AppendLine("Use [Udap.Identity.Provider2.db];");
sb.AppendLine("if not exists(select * from sys.server_principals where name = 'udap_user')");
sb.AppendLine("BEGIN");
sb.AppendLine("CREATE LOGIN udap_user WITH PASSWORD = 'udap_password1', DEFAULT_DATABASE =[Udap.Idp.db], CHECK_EXPIRATION = OFF, CHECK_POLICY = OFF;");
sb.AppendLine("END");
sb.AppendLine("IF NOT EXISTS(SELECT principal_id FROM sys.database_principals WHERE name = 'udap_user')");
sb.AppendLine("BEGIN");
sb.AppendLine("CREATE USER udap_user from LOGIN udap_user;");
sb.AppendLine("EXEC sp_addrolemember N'db_owner', N'udap_user';");
sb.AppendLine("END");
await configDbContext.Database.ExecuteSqlRawAsync(sb.ToString());
return 0;
}
}