private static TestServer CreateResourceServer(Action<OAuthIntrospectionOptions> configuration) {
var server = CreateAuthorizationServer();
var builder = new WebHostBuilder();
builder.UseEnvironment("Testing");
builder.ConfigureServices(services => {
services.AddAuthentication();
services.AddDistributedMemoryCache();
});
builder.Configure(app => {
app.UseOAuthIntrospection(options => {
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.Authority = server.BaseAddress.AbsoluteUri;
options.HttpClient = server.CreateClient();
// Run the configuration delegate
// registered by the unit tests.
configuration?.Invoke(options);
});
app.Map("/ticket", map => map.Run(async context => {
var ticket = new AuthenticateContext(OAuthIntrospectionDefaults.AuthenticationScheme);
await context.Authentication.AuthenticateAsync(ticket);
if (!ticket.Accepted || ticket.Principal == null || ticket.Properties == null) {
await context.Authentication.ChallengeAsync();
return;
}
context.Response.ContentType = "application/json";
// Return the authentication ticket as a JSON object.
await context.Response.WriteAsync(JsonConvert.SerializeObject(new {
Claims = from claim in ticket.Principal.Claims
select new { claim.Type, claim.Value },
Properties = from property in ticket.Properties
select new { Name = property.Key, property.Value }
}));
}));
app.Run(context => {
if (!context.User.Identities.Any(identity => identity.IsAuthenticated)) {
return context.Authentication.ChallengeAsync();
}
return context.Response.WriteAsync(context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value);
});
});
return new TestServer(builder);
}