Domenic Domenic - 10 months ago 77
ASP.NET (C#) Question

IdentityServer3 xBehave test

I wanted to write acceptance tests for my WebApi and IdentityServer. To keep things as simple as possible I copied the whole sample project from here but added another project, that essentially makes the same as the console client would but as a acceptance test.

The only scenario I got right now is this:

namespace SpecTesting
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using FluentAssertions;
using IdentityModel.Client;
using Xbehave;

public class JustLikeConsole
private static readonly string ServerUrl = "http://localhost:11111";
private static readonly string IdentityServerUrl = "http://localhost:5000";

private IDisposable webApp;
private IDisposable identityServer;
private HttpClient appClient;
private HttpClient identityServerClient;

public void Background()
"establish server"._(() =>
this.identityServer = Microsoft.Owin.Hosting.WebApp.Start<IdSrv.Startup>(IdentityServerUrl);
this.webApp = Microsoft.Owin.Hosting.WebApp.Start<Apis.Startup>(ServerUrl);
this.appClient = new HttpClient { BaseAddress = new Uri(ServerUrl) };
this.identityServerClient = new HttpClient { BaseAddress = new Uri(IdentityServerUrl) };
}).Teardown(() =>

public void SimplestScenario(HttpResponseMessage response)
var clientId = "silicon";
var clientSecret = "F621F470-9731-4A25-80EF-67A6F7C5F4B8";
var expectedJson = $"{{ client: '{clientId}' }}";

"get token"._(() =>
var client = new TokenClient(

var token = client.RequestClientCredentialsAsync("api1").Result;

"when calling the service"._(()
=> response = this.appClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/test"), CancellationToken.None).Result);

"it should return status code 'OK'"._(()
=> response.StatusCode.Should().Be(HttpStatusCode.OK));

"it should equal expected json"._(()
=> response.Content.ReadAsStringAsync().Result.Should().Be(expectedJson));

I now always get the status code 'unauthorized' instead of 'ok'. When I call the two servers via the console client, it works as expected. Very frustrating.

I replaced the "when calling a service" step with the following lines just to enhance the simplicity:

var client = new HttpClient();
var result = client.GetStringAsync($"{ServerUrl}/test").Result;

The problem is still the same: Now an HttpRequestException gets thrown (401 unauthorized).

Answer Source

In the meantime I found the reason why it wasn't working:

Turned out I have to use version 2.6.0 of IdentityServer3.AccessTokenValidation or earlier on the WebApi. As soon as I update to 2.7.0 or later it stops working. I didn't have time to find out what exactly has changed between the two releases and therefore what causes the problem. But I could isolate it to IdentityServer3.AccessTokenValidation