缘起ionic社区里的(ionic serve)时的跨域问题,有人在这里翻译了一篇文章,洋洋洒洒,从理论到实际,说的都很好。

不过有人在底下的评论里说的更加到位:

 

搜索了一下,果然啊,方便啊



不过还是要说一下在服务器上的配置,如此能够做到使ionic当作纯web来使用。

废话不多,上代码。

先上一个attribute,每次响应都带上这个header,允许其访问:

    public class AccessControlAllowOriginAttribute : System.Web.Http.Filters.ActionFilterAttribute  
    {
        public const string ALLOW_ORIGIN = "http://test.test.com";

        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", ALLOW_ORIGIN);
        }  
    }

在被允许调用的action或者controller上赋值此attribute:

    [AccessControlAllowOrigin]
    public class ValuesController : ApiController
    {
    }

完成。


考虑到正常来说也就一个被允许访问的站点,因此使用了一个string的const,当然多了也可以考虑变成string[]。

还可以使用动态的配置来加载这个string或者string[]。都可以。

public class AccessControlAllowOriginAttribute : System.Web.Http.Filters.ActionFilterAttribute  
{
    public static string[] ARRAY_ALLOW_ORIGIN = new string[] { "http://int-env.test.com", "http://prod-env.test.com" };

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        try
        {
            string origin = System.Web.HttpContext.Current.Request.Headers["Origin"];
            if (string.IsNullOrWhiteSpace(origin))
            {
                return;
            }
            origin = origin.ToLower();
            if (ARRAY_ALLOW_ORIGIN.Contains(origin))
            {
                System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", origin);
            }
        }
        catch (Exception ex)
        {}
    }  
}

当然了,由于Origin可以伪造,在任意允许了跨域访问的server上,无论是个别网站来源还是*的来源,都不是安全的,只是造成其风险的步骤稍微多了一点而已。

其安全性上还是要更多考虑一些。



附请求双方的一些关键字:

/token
post
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=uname&password=pwd

resp:

{
    "access_token": "ttttttttttttttttttt",
    "token_type": "bearer",
    "expires_in": 1209599,
    "userName": "uanme",
    ".issued": "Fri, 01 Jul 2016 05:38:12 GMT",
    ".expires": "Fri, 15 Jul 2016 05:38:12 GMT"
}
后续的token header:

Authorization : bearer token



 


Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐