0

我使用令牌身份验证为我的WebApi应用程序。单元测试Web API - 如何获得身份验证令牌

我在启动类以下ConfigureAuth方法:

 // Configure the application for OAuth based flow 
     PublicClientId = "self"; 
     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      Provider = new ApplicationOAuthProvider(PublicClientId), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      // In production mode set AllowInsecureHttp = false 
      AllowInsecureHttp = true 
     }; 

     // Enable the application to use bearer tokens to authenticate users 
     app.UseOAuthBearerTokens(OAuthOptions); 

和ApplicationOAuthProvider:

public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider 
{ 
    private readonly string _publicClientId; 

    public ApplicationOAuthProvider(string publicClientId) 
    { 
     if (publicClientId == null) 
     { 
      throw new ArgumentNullException("publicClientId"); 
     } 

     _publicClientId = publicClientId; 
    } 

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) 
    { 
     var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); 

     var user = await userManager.FindAsync(context.UserName, context.Password); 
     //ApplicationUser user = new ApplicationUser() { UserName ="a" }; 

     if (user == null) 
     { 
      context.SetError("invalid_grant", "The user name or password is incorrect."); 
      return; 
     } 

     ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, 
      OAuthDefaults.AuthenticationType); 
     ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, 
      CookieAuthenticationDefaults.AuthenticationType); 

     AuthenticationProperties properties = CreateProperties(user.UserName); 
     AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties); 
     context.Validated(ticket); 
     context.Request.Context.Authentication.SignIn(cookiesIdentity); 
    } 

所以,我应该叫/令牌和凭据传递拿到令牌。它有效,但我想为它创建单元测试。可能吗?

回答

3

要做到这一点的唯一方法是进行集成测试,该测试会断言整个管道测试 - 从请求到响应。在服务器上进行实际测试之前,您可以调用令牌端点来获取它,然后将其附加到响应中,然后在实际单元测试中使用它。我有一个样品,在这里使用MyTested.WebApi:

Sample

你可以做同样的没有测试库,这仅仅是如何做到这一点。

+0

样品溶液这样做,我设置HTTP配置时使用下面的行中我的单元测试方法不行.. –

0

我喜欢插拔配置的想法。 对于单元测试项目,我想使用特定的身份并获得可预测的LDAP数据。

config.Filters.Add(new WebApiSetIdentityFilter(config, identityName)); 

其中滤波器只是“黑客”的身份,替换字段我需要:

public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) 
{ 
    //This principal flows throughout the request. 
    context.Principal = new GenericPrincipal(new GenericIdentity(this.IdentityName, "LdapAuthentication"), new string[0]); 
}