缘起ionic社区里的(ionic serve)时的跨域问题,有人在这里翻译了一篇文章,洋洋洒洒,从理论到实际,说的都很好。html
不过有人在底下的评论里说的更加到位:web
搜索了一下,果真啊,方便啊跨域
不过仍是要说一下在服务器上的配置,如此可以作到使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