ionic ajax 跨域,解决 ionic 中的 CORS(跨域) 问题

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

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

9ea74ff8f23d0f512eb82b783e4ffd55.png

搜索了一下,果真啊,方便啊跨域

7b5b5c9b71b91f611c43a5c9c273728d.png

不过仍是要说一下在服务器上的配置,如此可以作到使ionic看成纯web来使用。安全

废话很少,上代码。服务器

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

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[]。ionic

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

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上,不管是个别网站来源仍是*的来源,都不是安全的,只是形成其风险的步骤稍微多了一点而已。

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

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

/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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值