在C#(web api)中测试经过身份验证的方法(使用bearer令牌)的正确方法

fdm*_*ion 7 c# authentication unit-testing bearer-token

我有一个Web API,其中包含许多方法,这些方法都需要有一个承载令牌才能使用.这些方法都从承载令牌中提取信息.

我想测试API是否在生成时正确填充了承载令牌.我正在使用Microsoft.Owin.Testing框架来编写测试.我有一个看起来像这样的测试:

[TestMethod]
public async Task test_Login() 
{
    using (var server = TestServer.Create<Startup>())
    {
        var req = server.CreateRequest("/authtoken");
        req.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        req.And(x => x.Content = new StringContent("grant_type=password&username=test&password=1234", System.Text.Encoding.ASCII));
        var response = await req.GetAsync();

        // Did the request produce a 200 OK response?
        Assert.AreEqual(response.StatusCode, System.Net.HttpStatusCode.OK);

        // Retrieve the content of the response
        string responseBody = await response.Content.ReadAsStringAsync();
        // this uses a custom method for deserializing JSON to a dictionary of objects using JSON.NET
        Dictionary<string, object> responseData = deserializeToDictionary(responseBody); 

        // Did the response come with an access token?
        Assert.IsTrue(responseData.ContainsKey("access_token"));

    }
}
Run Code Online (Sandbox Code Playgroud)

所以我能够检索代表令牌的字符串.但现在我想实际访问该令牌的内容,并确保提供了某些声明.

我将在实际经过身份验证的方法中使用以检查声明的代码如下所示:

var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;

var claimTypes = from x in claims select x.Type;

if (!claimTypes.Contains("customData"))
    throw new InvalidOperationException("Not authorized");
Run Code Online (Sandbox Code Playgroud)

所以我想要做的是,在我的测试本身内,提供持有者令牌字符串并重新获得User.Identity对象或以其他方式获得对令牌包含的声明的访问权.这就是我想测试我的方法是否正确地向令牌添加必要声明的方法.

"天真"的方法可能是在我的API中编写一个方法,它只返回给定的承载令牌中的所有声明.但感觉这应该是不必要的.在调用控制器的方法之前,ASP.NET以某种方式将给定的标记解码为对象.我想在我的测试代码中自己复制相同的操作.

可以这样做吗?如果是这样,怎么样?


编辑:我的OWIN启动类实例化我编码的身份验证令牌提供程序,它处理身份验证和令牌生成.在我的启动课上我有这个:

public void Configuration(IAppBuilder app)
{
    // Setup configuration object
    HttpConfiguration config = new HttpConfiguration();

    // Web API configuration and services
    // Configure Web API to use only bearer token authentication.
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    // configure the OAUTH server
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        //AllowInsecureHttp = false,
        AllowInsecureHttp = true, // THIS HAS TO BE CHANGED BEFORE PUBLISHING!

        TokenEndpointPath = new PathString("/authtoken"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new API.Middleware.MyOAuthProvider()
    };

    // Now we setup the actual OWIN pipeline.

    // setup CORS support
    // in production we will only allow from the correct URLs.
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

    // insert actual web API and we're off!
    app.UseWebApi(config);
}
Run Code Online (Sandbox Code Playgroud)

以下是我的OAuth提供商提供的相关代码:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{

    // Will be used near end of function
    bool isValidUser = false;

    // Simple sanity check: all usernames must begin with a lowercase character
    Match testCheck = Regex.Match(context.UserName, "^[a-z]{1}.+$");
    if (testCheck.Success==false)
    {
        context.SetError("invalid_grant", "Invalid credentials.");
        return;
    }

    string userExtraInfo;
    // Here we check the database for a valid user.
    // If the user is valid, isValidUser will be set to True.
    // Invalid authentications will return null from the method below.
    userExtraInfo = DBAccess.getUserInfo(context.UserName, context.Password);
    if (userExtraInfo != null) isValidUser = true;

    if (!isValidUser)
    {
        context.SetError("invalid_grant", "Invalid credentials.");
        return;
    }

    // The database validated the user. We will include the username in the token.
    string userName = context.UserName;

    // generate a claims object
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);

    // add the username to the token
    identity.AddClaim(new Claim(ClaimTypes.Sid, userName));

    // add the custom data on the user to the token.
    identity.AddClaim(new Claim("customData", userExtraInfo));

    // store token expiry so the consumer can determine expiration time
    DateTime expiresAt = DateTime.Now.Add(context.Options.AccessTokenExpireTimeSpan);
    identity.AddClaim(new Claim("expiry", expiresAt.ToString()));

    // Validate the request and generate a token.
    context.Validated(identity);

}
Run Code Online (Sandbox Code Playgroud)

单元测试需要确保声明customData实际上存在于身份验证令牌中.因此,我需要一种方法来评估提供的令牌,以测试它包含哪些声明.


编辑2:我花了一些时间查看Katana源代码并在线搜索其他一些帖子,看起来我在IIS上托管这个应用程序很重要,所以我会使用SystemWeb.看起来SystemWeb对令牌使用机密钥加密.它看起来像AccessTokenFormat选项中的参数在这里是相关的.

所以现在我想知道的是,如果我可以基于这些知识实例化我自己的"解码器".假设我只会在IIS上托管,我可以实例化一个解码器,然后可以解码令牌并将其转换为Claim对象吗?

关于这方面的文档有点稀疏,代码似乎把你扔到了一个地方,很多东西试图直接在我脑海里.


编辑3:我发现了一个包含应该是承载令牌解串器的项目.我在其"API"库中修改了代码,并一直尝试使用它来解密由我的API生成的令牌.

<machineKey...>使用Microsoft的PowerShell脚本生成了一个值,并将其放在API本身的Web.config文件和测试项目中的App.confg文件中.

然而,令牌仍然无法解密.我收到一个Exception抛出:System.Security.Cryptography.CryptographicException带有消息"Error occurred during a cryptographic operation."以下是错误的堆栈跟踪:

at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.HomogenizeErrors(Func`2 func, Byte[] input)
at System.Web.Security.Cryptography.HomogenizingCryptoServiceWrapper.Unprotect(Byte[] protectedData)
at System.Web.Security.MachineKey.Unprotect(ICryptoServiceProvider cryptoServiceProvider, Byte[] protectedData, String[] purposes)
at System.Web.Security.MachineKey.Unprotect(Byte[] protectedData, String[] purposes)
at MyAPI.Tests.BearerTokenAPI.MachineKeyDataProtector.Unprotect(Byte[] protectedData) in D:\Source\MyAPI\MyAPI.WebAPI.Tests\BearerTokenAPI.cs:line 251
at MyAPI.Tests.BearerTokenAPI.SecureDataFormat`1.Unprotect(String protectedText) in D:\Source\MyAPI\MyAPI.WebAPI.Tests\BearerTokenAPI.cs:line 287
Run Code Online (Sandbox Code Playgroud)

在这一点上,我很难过.在整个项目中将MachineKey值设置为相同,我不明白为什么我无法解密令牌.我猜测加密错误是故意模糊的,但我不知道从哪里开始现在解决这个问题.

而我想做的就是测试令牌包含单元测试中所需的数据.... :-)

fdm*_*ion 14

我终于能够找到解决方案了.我在我的Startup类中添加了一个公共变量,它公开了OAuthBearerAuthenticationOptions传递给UseBearerTokenAuthentication方法的对象.从那个对象,我能够调用AccessTokenFormat.Unprotect并获得一个解密的令牌.

我还重写了我的测试以分别实例化Startup类,以便我可以访问测试中的值.

我仍然不明白为什么MachineKey的东西不起作用,为什么我无法直接取消保护令牌.似乎只要MachineKey匹配,我就能够解密令牌,甚至手动解密.但至少这似乎有效,即使它不是最好的解决方案.

这可能会更干净地完成,例如,Startup类可能会以某种方式检测它是否在测试中启动并以其他方式将对象传递给测试类,而不是让它在微风中挂在那里.但是现在这似乎完全符合我的需要.

我的启动类以这种方式公开变量:

public partial class Startup
{
    public OAuthBearerAuthenticationOptions oabao;

    public void Configuration(IAppBuilder app)
    {

        // repeated code omitted

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        oabao = new OAuthBearerAuthenticationOptions();
        app.UseOAuthBearerAuthentication(oabao);

        // insert actual web API and we're off!
        app.UseWebApi(config);

    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试现在看起来像这样:

[TestMethod]
public async Task Test_SignIn()
{
    Startup owinStartup = new Startup();
    Action<IAppBuilder> owinStartupAction = new Action<IAppBuilder>(owinStartup.Configuration);

    using (var server = TestServer.Create(owinStartupAction))
    {
        var req = server.CreateRequest("/authtoken");
        req.AddHeader("Content-Type", "application/x-www-form-urlencoded");

        // repeated code omitted

        // Is the access token of an appropriate length?
        string access_token = responseData["access_token"].ToString();
        Assert.IsTrue(access_token.Length > 32);

        AuthenticationTicket token = owinStartup.oabao.AccessTokenFormat.Unprotect(access_token);

        // now I can check whatever I want on the token.
    }
}
Run Code Online (Sandbox Code Playgroud)

希望我的所有努力都能帮助其他人尝试做类似的事情.