我正在尝试在 ASP MVC 4 WebAPI 中连接自定义成员身份,但我无法弄清楚如何替换当前的提供者。我在提供者的构造函数中放置了一个断点,它永远不会落在它上面。运行下面的测试会在 GetResponse 调用上给我一个“401 Unauthorized”消息,因此 SOMETHING 正在尝试验证请求。我哪里错了?几乎相同的代码在 ASP MVC 4 站点(不是 WebAPI)中运行。
我知道测试中的一般逻辑是有效的,因为如果我删除 Authorize 属性,测试就会成功。
这是我的 WebConfig:
<authentication mode="Forms" />
<profile enabled="false">
<providers>
<clear/>
</providers>
</profile>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear/>
<add name="MyMembershipProvider"
type="CustomWebApiMembershipProvider"
applicationName="AppName"/>
</providers>
</membership>
<roleManager enabled="true" defaultProvider="MyWebApiRoleProvider">
<providers>
<clear/>
<add name="MyWebApiRoleProvider" type="CustomWebApiRoleProvider" />
</providers>
</roleManager>
这是我的提供者。
public class CustomWebApiMembershipProvider: MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
return password.Contains("please");
}
public CustomWebApiMembershipProvider()
{
var x = "hello";
}
}
这是我的控制器:
[Authorize]
public class TestApiSecureController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new string[] {"CustomWebApi Secured Access"};
}
}
这是我的测试:
[Test]
public void Authorize_WhenApiKeyProvided_ReturnsValidResponse()
{
var request = WebRequest.Create("http://localhost:4011/api/TestApiSecure") as HttpWebRequest;
AddAuthorizationInfo(request, "username", "pleaseLetMeIn");
//we keep timing out when stepping through in debug, so set huge timeout
request.Timeout = 100000;
var response = request.GetResponse();
var reader = new StreamReader(response.GetResponseStream());
var result = reader.ReadToEnd();
Assert.IsTrue(result.Contains("CustomWebApi"));
}
private void AddAuthorizationInfo(HttpWebRequest request, string username, string password)
{
var usernamePwString = username + ":" + password;
var authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(usernamePwString));
request.Headers["Authorization"] = "Basic" + authInfo;
}