gpt4 book ai didi

unit-testing - 单元测试 Web API - 如何获取身份验证 token

转载 作者:行者123 更新时间:2023-12-03 09:17:33 24 4
gpt4 key购买 nike

我对我的 WebApi 应用程序使用 token 身份验证。

我在 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 并传递凭据来获取 token 。它有效,但我想为其创建单元测试。可能吗?

最佳答案

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

Sample

您可以在没有测试库的情况下执行相同的操作,这只是操作方法。

关于unit-testing - 单元测试 Web API - 如何获取身份验证 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com