Reputation: 980
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?
Upvotes: 1
Views: 446
Reputation: 1643
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
Upvotes: 2