Iframe, cross-domain cookies, p3p policy, and safari with error: A required anti-forgery token was not supplied or was invalid

前端 未结 1 1517
旧巷少年郎
旧巷少年郎 2020-12-08 11:41

I asked this question a while back and found that IE blocks cross-domain cookies in an iframe unless you set a p3p policy. So far, the p3p fix has worked beautifully in ie.

相关标签:
1条回答
  • 2020-12-08 12:38

    The issue is that Safari does not allow a cookie to be set in an iframe unless the user interacts with that iframe. For some, that means clicking a link. I found a better solution which is to do a redirect.

    First, I put this form on my page. Actually, I put it in the masterpage that is used by every view served in the iframe.

    <% if(SecurityHelper.BrowserIsSafari) { %>
        <% using (Html.BeginForm("SafariRedirect", "Framed", FormMethod.Post, new { id="safari-fix-form" })) { %>
           <%: Html.Hidden("safariRedirectUrl")%>
        <% } %>
    <% } %>
    

    Because I only want this to work when the user is using safari, I created this property in a static helper class to check the useragent

    public static bool BrowserIsSafari
    {
        get { return HttpContext.Current.Request.UserAgent.ToLower().IndexOf("safari") >= 0; }
    }
    

    Then, in my controller, I have the following action

    [HttpPost]
    public ActionResult SafariRedirect(string safariRedirectUrl)
    {
        Response.Cookies.Add(new HttpCookie("safari_cookie_fix", "cookie ok"));
    
        return Redirect(safariRedirectUrl);
    }
    

    In my masterpage, in the header, I have my script declared within the same if statement that determines if the form is rendered. In my script file, I have this jquery

    $(function () {
    
        if ($.browser.safari == true && document.cookie.indexOf("safari_cookie_fix") == -1) {
            var url = location.href;
    
            $('#safariRedirectUrl').val(url);
            $('#safari-fix-form').submit();
        }
    
    });
    

    The first time the iframe loads a page, if it is safari and the cookie isn't set, the form is posted, the cookie set, and the user is redirected back to the same url.

    0 讨论(0)
提交回复
热议问题