我想为我的WebApi和IdentityServer编写验收测试。为了让事情尽可能简单,我复制了here的整个示例项目,但又添加了另一个项目,它基本上和控制台客户端一样,但是作为验收测试。IdentityServer3 xBehave测试
我现在唯一的情况是这样的:
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;
[Background]
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(() =>
{
this.identityServerClient.Dispose();
this.appClient.Dispose();
this.webApp.Dispose();
this.identityServer.Dispose();
});
}
[Scenario]
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(
$"{IdentityServerUrl}/connect/token",
clientId,
clientSecret);
var token = client.RequestClientCredentialsAsync("api1").Result;
this.appClient.SetBearerToken(token.AccessToken);
});
"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));
}
}
}
我现在总是得到状态代码“未经授权”,而不是“OK”。当我通过控制台客户端调用这两个服务器时,它按预期工作。非常令人沮丧。
更新 我取代了“呼叫服务时”的步骤与下面的行只是为了增强简洁:
var client = new HttpClient();
client.SetBearerToken(token.AccessToken);
var result = client.GetStringAsync($"{ServerUrl}/test").Result;
的问题仍然是相同的:现在的HttpRequestException被抛出(401未经授权)。
此问题是后续的:http://stackoverflow.com/questions/40425587/identityserver3-principals-always-null – Domenic
它并不容易,因为令牌是在“获取令牌”下方的场景中没有设置appClient? cp-paste将令牌提取到每个场景中,并验证它不是那个 –
没有用。我已更新问题 – Domenic