单元测试Web API - 如何获取身份验证令牌

时间:2016-03-06 22:56:49

标签: unit-testing authentication asp.net-web-api oauth asp.net-web-api2

我为我的WebApi应用程序使用token auth。

我在Startup类中有以下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);
    }

所以,我应该调用/ Token并传递凭据以获取令牌。它有效,但我想为它创建单元测试。有可能吗?

2 个答案:

答案 0 :(得分:3)

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

Sample

你可以在没有测试库的情况下做同样的事情,这就是如何做到的。

答案 1 :(得分:0)

我喜欢可插拔配置的想法。 对于单元测试项目,我想使用特定的身份并从LDAP获取可预测的数据。因此,在设置http配置时,我在单元测试方法中使用以下行:

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

过滤器只是&#34; hacks&#34;身份,取代我需要的领域:

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]);
}