集成测试的Web API和[授权] [英] Integration Test Web Api With [Authorize]

查看:254
本文介绍了集成测试的Web API和[授权]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我发现的点点滴滴已经启发了我一些关于[授权]标记,但没有能解决我的问题。

So I've found bits and pieces that have enlightened me some on the [Authorize] tag, but nothing that solves my problem.

我的情况是,我有我想用RestSharp集成测试打的Web API方法。然而RestSharp是让我的登录页面,而不是调用的结果。

My scenario is that I have Web Api methods that I want to hit with integration tests using RestSharp. However RestSharp is getting my login page, instead of the results of the call.

[Authorize]
public Item GetItem([FromBody] int id) 
{
   return service.GetItem(id);
}

该产品采用了自定义登录系统,什么我真的想将禁用[授权]徽章仅用于集成测试的一种方式。不过,我看你能允许匿名用户,这将禁用的徽章,所以在溶液中,我有一个集成测试项目,在该项目中我有一个App.config文件。在该文件中,我把:

The product uses a custom login system, and what I would REALLY like would be a way to disable the [Authorize] badge only for integration tests. However I read that you can allow anonymous users and it would 'disable' the badge, so in the solution, I have an integration tests project, and in that project I have an App.config file. In that file I put:

 <location>
  <system.web>
   <authorization>
     <allow users="?"/>
    </authorization>
  </system.web>
 </location>

但是,这并不似乎任工作。任何解释,这是怎么回事,为什么它不工作,可以做些什么来得到这个工作将是极大的AP preciated。

But this doesn't appear to be working either. Any explanation as to what's going on, why it's not working and what can be done to get this working would be greatly appreciated.

我试图设置,但Thread.CurrentPrincipal中没有工作(也许我做错了 - 你可以设置任何,在code被授权?)。认证是一个HttpModule处理有没有什么帮助的。

I have attempted to set a Thread.CurrentPrincipal but that didn't work (maybe I did it wrong - can you set "anything" to be authorized in the code?). Authentication is handled in an httpmodule if that helps at all.

推荐答案

下面是你应该如何设置 Thread.CurrentPrincipal中。这样的消息处理程序添加到您的Web API项目,并在 WebApiConfig.cs 的像注册方法中添加处理程序这样: config.MessageHandlers.Add(新MyTestHandler());

Here is how you should set the Thread.CurrentPrincipal. Add a message handler like this to your Web API project and add the handler in the Register method of WebApiConfig.cs like so: config.MessageHandlers.Add(new MyTestHandler());.

public class MyTestHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
                                 HttpRequestMessage request,
                                     CancellationToken cancellationToken)
    {
        var local = request.Properties["MS_IsLocal"] as Lazy<bool>;
        bool isLocal = local != null && local.Value;

        if (isLocal)
        {
            if (request.Headers.GetValues("X-Testing").First().Equals("true"))
            {
                var dummyPrincipal = new GenericPrincipal(
                                        new GenericIdentity("dummy", "dummy"),
                                          new[] { "myrole1" });

                Thread.CurrentPrincipal = dummyPrincipal;

                if (HttpContext.Current != null)
                    HttpContext.Current.User = dummyPrincipal;
            }
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

此处理程序设置身份验证的主体,使所有的 [授权] 开心。有这种方法的风险的一个元素。仅用于测试,你应该插入此处理到Web API管线。如果您在您的生产code管道(有意或无意)插件此处理程序,它基本上击败你的身份验证机制。为了降低这种风险在一定程度上(希望的,API也不会在本地访问),我检查,以确保访问是局部的,有一个头 X-测试与值真正

This handler sets an authenticated principal to make all your [Authorize] happy. There is an element of risk with this approach. Only for testing, you should plug this handler into the Web API pipeline. If you plug this handler in to the pipeline (intentional or otherwise) in your production code, it basically defeats your authentication mechanism. To mitigate the risk to some extent (hoping API is not accessed locally), I check to ensure the access is local and that there is a header X-Testing with a value of true.

从RestSharp,添加自定义标题。

From RestSharp, add the custom header.

var request = new RestRequest(...);
request.AddHeader("X-Testing", "true");

BTW,集成测试,我宁愿在内存中使用的主机,而不是Web托管。这样一来,网络API在相同的测试项目运行,你可以做你想做的事情什么,没有在生产中打破东西的恐惧。有关内存的主机的详细信息,请参阅这个并的这个

这篇关于集成测试的Web API和[授权]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆