토큰 유효성 검사에 IdentityServer4를 사용하는 API가 있습니다. 인 메모리 TestServer를 사용하여이 API를 단위 테스트하고 싶습니다. in-memory TestServer에서 IdentityServer를 호스팅하고 싶습니다.메모리 내 IdentityServer를 사용한 통합 테스트
IdentityServer에서 토큰을 생성 할 수있었습니다.
이 내가 얼마나 멀리 왔는지,하지만 난
API를 사용하는 [권한 부여]가 다른 정책을 -attribute "http://localhost:54100/.well-known/openid-configuration에서 구성을 가져올 수 없습니다"오류가 발생합니다. 이것이 내가 테스트하고 싶은 것입니다.
이 작업을 수행 할 수 있습니까? 내가 뭘 잘못하고 있습니까? IdentityServer4의 소스 코드를 살펴 보려고했지만 유사한 통합 테스트 시나리오를 발견하지 못했습니다.
protected IntegrationTestBase()
{
var startupAssembly = typeof(Startup).GetTypeInfo().Assembly;
_contentRoot = SolutionPathUtility.GetProjectPath(@"<my project path>", startupAssembly);
Configure(_contentRoot);
var orderApiServerBuilder = new WebHostBuilder()
.UseContentRoot(_contentRoot)
.ConfigureServices(InitializeServices)
.UseStartup<Startup>();
orderApiServerBuilder.Configure(ConfigureApp);
OrderApiTestServer = new TestServer(orderApiServerBuilder);
HttpClient = OrderApiTestServer.CreateClient();
}
private void InitializeServices(IServiceCollection services)
{
var cert = new X509Certificate2(Path.Combine(_contentRoot, "idsvr3test.pfx"), "idsrv3test");
services.AddIdentityServer(options =>
{
options.IssuerUri = "http://localhost:54100";
})
.AddInMemoryClients(Clients.Get())
.AddInMemoryScopes(Scopes.Get())
.AddInMemoryUsers(Users.Get())
.SetSigningCredential(cert);
services.AddAuthorization(options =>
{
options.AddPolicy(OrderApiConstants.StoreIdPolicyName, policy => policy.Requirements.Add(new StoreIdRequirement("storeId")));
});
services.AddSingleton<IPersistedGrantStore, InMemoryPersistedGrantStore>();
services.AddSingleton(_orderManagerMock.Object);
services.AddMvc();
}
private void ConfigureApp(IApplicationBuilder app)
{
app.UseIdentityServer();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var options = new IdentityServerAuthenticationOptions
{
Authority = _appsettings.IdentityServerAddress,
RequireHttpsMetadata = false,
ScopeName = _appsettings.IdentityServerScopeName,
AutomaticAuthenticate = false
};
app.UseIdentityServerAuthentication(options);
app.UseMvc();
}
그리고 내 단위 테스트에서
:private HttpMessageHandler _handler;
const string TokenEndpoint = "http://localhost/connect/token";
public Test()
{
_handler = OrderApiTestServer.CreateHandler();
}
[Fact]
public async Task LeTest()
{
var accessToken = await GetToken();
HttpClient.SetBearerToken(accessToken);
var httpResponseMessage = await HttpClient.GetAsync("stores/11/orders/asdf"); // Fails on this line
}
private async Task<string> GetToken()
{
var client = new TokenClient(TokenEndpoint, "client", "secret", innerHttpMessageHandler: _handler);
var response = await client.RequestClientCredentialsAsync("TheMOON.OrderApi");
return response.AccessToken;
}
덕분에 많은 @Lutando. 첫 번째 대답은 올바른 방향으로 나를 가리켰다. –
아, 괜찮습니다. @emedbo 가짜 테스트를 두 번 할 수 있다고 생각했습니다. 하지만 작동합니다. – Lutando
가짜 프로젝트는 약 20 개의 파일로 구성되어 있으므로 책임이 있습니다. 위쪽은 꽤 산뜻하지만! 나는 나보다 많은 지식을 가진 누군가가 덜 복잡하게 만들 수 있다고 확신한다. –