我正在为我的微服务身份验证和授权编写集成测试。我正在将IdentityServer4与内存中存储一起使用,我的代码如下所示;
编辑:我在正在使用的内存设置中添加了SQLite。不知道我是否需要IS4 InMemory存储。
var builder = services
.AddIdentityServer(options =>
{
options.IssuerUri = "https://my.services.is4host";
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
});
var migrationAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var inMemorySqlite = new SqliteConnection("Data Source=:memory:");
inMemorySqlite.Open();
services
.AddDbContext<SecurityDbContext>(
options => options.UseSqlite(inMemorySqlite,
sql => sql.MigrationsAssembly(migrationAssembly)));
// Migrate the database
var context = services.BuildServiceProvider().GetService<SecurityDbContext>();
context.Database.Migrate();
builder
.AddInMemoryClients(IS4Config.GetClients())
.AddInMemoryIdentityResources(IS4Config.GetIdentityResources())
.AddInMemoryApiResources(IS4Config.GetAPIResources())
.AddTestUsers(new List<TestUser>
{
new TestUser {
SubjectId = Guid.NewGuid().ToString(),
Claims = new List<Claim> {
new Claim(JwtClaimTypes.Subject, MyDemoUser.ElevatedUser.UserName),
new Claim(JwtClaimTypes.Email, MyDemoUser.ElevatedUser.Email),
new Claim(JwtClaimTypes.Role, MyDemoUser.ElevatedUser.Roles[0]),
new Claim(JwtClaimTypes.Role, MyDemoUser.ElevatedUser.Roles[1])
},
IsActive = true,
Password = MyDemoUser.ElevatedUser.Password,
Username = MyDemoUser.ElevatedUser.UserName
},
new TestUser {
SubjectId = Guid.NewGuid().ToString(),
Claims = new List<Claim> {
new Claim(JwtClaimTypes.Subject, MyDemoUser.WorkstationUser.UserName),
new Claim(JwtClaimTypes.Email, MyDemoUser.WorkstationUser.Email),
new Claim(JwtClaimTypes.Role, MyDemoUser.WorkstationUser.Roles[0])
},
IsActive = true,
Password = MyDemoUser.WorkstationUser.Password,
Username = MyDemoUser.WorkstationUser.UserName
}
});
我的测试如下:
var is4Host = new WebApplicationTestFactory<Services.IS4Host.Startup>();
var client = is4Host.CreateClient();
var disco = await client.GetDiscoveryDocumentAsync("https://My.services.is4host");
if (disco.IsError)
{
Console.WriteLine(disco.Error);
return false;
}
// request token
var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = MyClient.ClientId,
ClientSecret = MyClient.ClientSecret,
Scope = MyApiResource.Gateway.Name,
UserName = user.UserName,
Password = user.Password
});
if (tokenResponse.IsError)
{
Console.WriteLine(tokenResponse.Error);
return false;
}
Console.WriteLine(tokenResponse.Json);
Console.WriteLine("\n\n");
return true;
我正在将记录添加到内存存储中,但是我不断从IS4中获得以下响应
{
"error": "invalid_grant",
"error_description": "invalid_username_or_password"
}