Uploadify - MVC3: HTTP 302 redirect error (due to asp.net authentication)

I use the uploadify to bulkupload function, and I get a 302 redirect error. I assume this is because the asp.net authentication cookie token is not passed back to the script call.

I downloaded the work in a regular mvc3 application with bare bones, but when I tried to integrate it into a secure asp.net mvc3 application, it tries to redirect to an account / signature.

I have an authentication token (@auth) that returns as a long string in the view, but I still get a 302 redirect error.

Any ideas on how to send cookie authentication data?

View:

 @{
     string auth = @Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
     }


<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function () {
        jQuery("#bulkupload").uploadify({
            'uploader': '@Url.Content("~/Scripts/uploadify.swf")',
            'cancelImg': '/Content/themes/base/images/cancel.png',
            'buttonText': 'Browse Files',
            'script': '/Creative/Upload/',
            scriptData: { token: "@auth" }, 
            'folder': '/uploads',
            'fileDesc': 'Image Files',
            'fileExt': '*.jpg;*.jpeg;*.gif;*.png',
            'sizeLimit': '38000',
            'multi': true,
            'auto': true,
              'onError'     : function (event,ID,fileObj,errorObj) {
      alert(errorObj.type + ' Error: ' + errorObj.info);
    }
        });
    }); 
    </script> 

Controller:

public class CreativeController : Controller
{
    public string Upload(HttpPostedFileBase fileData, string token)
    {
      ...
    }
}

UPDATE: , IE9, Chrome (Chrome 302). FF .

- , Chrome FF?

+3
1

, uploadize asp.net mvc3. , , , , . , cookie Uploadify HTTP Post cookie .

:

/// <summary>
/// A custom version of the <see cref="AuthorizeAttribute"/> that supports working
/// around a cookie/session bug in Flash.  
/// </summary>
/// <remarks>
/// Details of the bug and workaround can be found on this blog:
/// http://geekswithblogs.net/apopovsky/archive/2009/05/06/working-around-flash-cookie-bug-in-asp.net-mvc.aspx
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class TokenizedAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// The key to the authentication token that should be submitted somewhere in the request.
    /// </summary>
    private const string TOKEN_KEY = "authCookie";

    /// <summary>
    /// This changes the behavior of AuthorizeCore so that it will only authorize
    /// users if a valid token is submitted with the request.
    /// </summary>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        string token = httpContext.Request.Params[TOKEN_KEY];

        if (token != null)
        {
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(token);

            if (ticket != null)
            {
                var identity = new FormsIdentity(ticket);
                string[] roles = System.Web.Security.Roles.GetRolesForUser(identity.Name);
                var principal = new GenericPrincipal(identity, roles);
                httpContext.User = principal;
            }
        }

        return base.AuthorizeCore(httpContext);
    }
}

, cookie ViewData, Uploadify. , Uploadify .

    [Authorize]
    public ActionResult UploadifyUploadPartial()
    {
        ViewBag.AuthCookie = Request.Cookies[FormsAuthentication.FormsCookieName] == null
                                 ? string.Empty
                                 : Request.Cookies[FormsAuthentication.FormsCookieName].Value;
        return PartialView("UploadifyUpload");
    }

UploadifyUpload. JavaScript, Uploadify. , . , authCookie scriptData ViewData UploadifyUploadPartial.

@if (false)
{
    <script src="../../Scripts/jquery-1.5.1-vsdoc.js" type="text/javascript"></script>
}
@{
    ViewBag.Title = "Uploadify";
}
<script src="@Url.Content("~/Scripts/plugins/uploadify/swfobject.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/plugins/uploadify/jquery.uploadify.v2.1.4.min.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Scripts/plugins/uploadify/uploadify.css")" rel="stylesheet" type="text/css" />
<script>
    $(document).ready(function () {
        CreateUploadifyInstance("dir-0");
    });
    function CreateUploadifyInstance(destDirId) {
        var uploader = "@Url.Content("~/Scripts/plugins/uploadify/uploadify.swf")";
        var cancelImg = "@Url.Content("~/Scripts/plugins/uploadify/cancel.png")";
        var uploadScript = "@Url.Content("~/Upload/UploadifyUpload")";
        var authCookie = "@ViewBag.AuthCookie";
        $('#uploadifyHiddenDummy').after('<div id="uploadifyFileUpload"></div>');
        $("#uploadifyFileUpload").uploadify({
            'uploader': uploader,
            'cancelImg': cancelImg,
            'displayData': 'percentage',
            'buttonText': 'Select Session...',
            'script': uploadScript,
            'folder': '/uploads',
            'fileDesc': 'SunEye Session Files',
            'fileExt': '*.son2',
            'scriptData'  : {'destDirId':destDirId, 'authCookie': authCookie},
            'multi': false,
            'auto': true,
            'onCancel': function(event, ID, fileObj, data) {
                //alert('The upload of ' + ID + ' has been canceled!');
            },
            'onError': function(event, ID, fileObj, errorObj) {
                alert(errorObj.type + ' Error: ' + errorObj.info);
            },
            'onAllComplete': function(event, data) {
                $("#treeHost").jstree("refresh");
                //alert(data.filesUploaded + ' ' + data.errors);
            },
            'onComplete': function(event, ID, fileObj, response, data) {
                alert(ID + " " + response);
            }
        });
    }
    function DestroyUploadifyInstance() {
        $("#uploadifyFileUpload").unbind("uploadifySelect");
        swfobject.removeSWF('uploadifyFileUploadUploader');
        $('#uploadifyFileUploadQueue').remove();
        $('#uploadifyFileUploadUploader').remove();
        $('#uploadifyFileUpload').remove();
    }
</script>
<div id="uploadifyHiddenDummy" style="visibility:hidden"></div>
<div id="uploadifyFileUpload">
</div>

, , TokenizedAuthorize Authorize:

    [HttpPost]
    [TokenizedAuthorize]
    public string UploadifyUpload(HttpPostedFileBase fileData)
    {
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Request.Form["authCookie"]);
        if (ticket != null)
        {
            var identity = new FormsIdentity(ticket);
            if (!identity.IsAuthenticated)
            {
                return "Not Authenticated";
            }
        }
        // Now parse fileData...
    }

, , UploadifyUploadPartial Html.Action Helper , Uploaded Widget:

@Html.Action("UploadifyUploadPartial", "YourUploadControllerName")

. FF, Chrome IE 9. , .

+5

All Articles