ASP.NET MVC User Authentication failure when using AJAX

I'm writing an ASP.NET MVC3 web application and user authentication fails (user is not authenticated) when I'm calling an action method with Ajax. My call looks like this:

$(function () {
                $("#picture").makeAsyncUploader({
                    upload_url: '@Url.Action("AsyncUpload", "Profile")',
                    flash_url: '/Scripts/swfupload.swf',
                    button_image_url: '/Scripts/blankButton.png'
                });
            });

where makeAsyncUploader is a function in a separate js file that handles all AJAX stuff. I've tried debugging the application, and it looks like no cookies are being sent to me with the request. Does anyone know what's the problem?

Answers


I know it's quite old question but I had exactly the same problem today so I will answer it.

There is a bug in the Flash plg for Firefox. It doesn't send cookie when uploading files. My solution:

1) Create new authorize attribute

  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class FlashAuthorizeAttribute : AuthorizeAttribute
    {
        private const string AUTH_TOKEN = "AuthenticationToken4Flash";
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            string authToken = httpContext.Request.Params[AUTH_TOKEN];
            if (authToken != null)
            {
                FormsAuthenticationTicket authForm = FormsAuthentication.Decrypt(authToken);
                if (authForm != null)
                {
                    FormsIdentity formIdentity = new FormsIdentity(authForm);
                    string[] userRoles = System.Web.Security.Roles.GetRolesForUser(formIdentity.Name);
                    GenericPrincipal userPrincipal = new GenericPrincipal(formIdentity, userRoles);
                    httpContext.User = userPrincipal;
                }
            }
            return base.AuthorizeCore(httpContext);
        }
    }

2) Controller

   [FlashAuthorize]
    public ActionResult AsyncUpload()
    {
        HttpPostedFileBase file = Request.Files[0];
    }

3) Modify your js (formData, scriptData didn't work for me so I added a query string)

      upload_url: '@Url.Action("AsyncUpload", "Profile")' +'?AuthenticationToken4Flash=' + '@(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)',

I hope it will help someone


Need Your Help

Gollum wiki for multiple projects

wiki web-farm gollum-wiki

I like Gollum for wiki, but seems to be always one project/topic specific.

MediaRecorder.AudioSource.DEFAULT blocking audio from call

android audio record android-mediarecorder

I am working on an application that records my own voice (using AudioSource.MIC or AudioSource.DEFAULT) when a call is made or received, using MediaRecorder. The problem that I'm having is that, wh...