ASP.NET MVC - Is.Local - 可以从开发环境访问控制器

时间:2017-10-26 14:21:12

标签: c# asp.net-mvc

我正在构建一个API,允许我的应用程序从MSSQL后端访问必要的数据。 API应用程序(ASP.NET MVC Web API)和调用者(基于PHP的应用程序)都将在同一服务器上运行。根据另一个StackOverflow问题的答案,我实现了以下LocalFilter:

// REFERENCE https://stackoverflow.com/questions/14858787/lock-down-asp-net-mvc-app-administration-site-to-localhost-only/24283809#24283809
public class LocalFilter : AuthorizeAttribute
{
    public bool ThrowSecurityException { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isLocal = httpContext.Request.IsLocal;
        if (!isLocal && ThrowSecurityException)
            throw new SecurityException();
        return isLocal;
    }
}

我用它装饰了许多控制器。

`

   [LocalFilter]
    [RoutePrefix("Hotels")]
    public class HotelsController : ApiController
    {
        UnitOfWork worker = new UnitOfWork();

        [Route("")]
        public string Get()
        {
            List<HotelDTO> dtoList = Mapper.Map<List<Property>, List<HotelDTO>>(worker.PropertiesRepo.Get(e => e.PropertyTypeID == 3).ToList());
            foreach(HotelDTO dto in dtoList) {
                dto.SliderImages = Mapper.Map<List<Image>, List<ImageDTO>>(worker.ImageRepo.Get(e => e.PropID == dto.ID && e.CategoryID == 2).ToList());
                dto.GalleryImages = Mapper.Map<List<Image>, List<ImageDTO>>(worker.ImageRepo.Get(e => e.PropID == dto.ID && e.CategoryID == 1).ToList());
            }

            return JsonConvert.SerializeObject(dtoList);
        }  /// MORE CODE FOLLOWS

`当我尝试从浏览器访问端点时,此过滤器按预期工作(我收到错误),我可以通过开发机器上的PHP脚本访问它。 / p>

    class APIWorker {

 const BASE_PATH = "http://www.mywebsite.com";
 // const BASE_PATH = "http://localhost:57263/";
    const AUTH_PATH =  "token";

public function getToken()  {

$body = Unirest\Request\Body::form($this->credentials);
$response = Unirest\Request::post(self::BASE_PATH . self::AUTH_PATH, array("Accept" => "application/json"), $body );
$this->token = $response->body->access_token;
} 


function getJSON(String $endPoint) {
    if(session_status() !== PHP_SESSION_ACTIVE) { session_start (); }

$url = self::BASE_PATH . $endPoint;

$credentials = $_SESSION["auth"] ?? ""; 

if($credentials != "") {
    $headers = array("Authorization" => "Bearer " . $credentials);
} else {
    $headers = array();
}

$response = Unirest\Request::get($url, $headers);

return json_decode($response->body);
}

对于我(有限的)理解,情况应该不是这样。 PHP脚本当前不在(在测试期间)与ASP.NET MVC Web API在同一服务器/机器上。为什么Request.IsLocal返回true并且如何修复它以便远程脚本无法访问数据?

感谢。

0 个答案:

没有答案