0

I am using Asp.net MVC4 Jquery ajax and i am passing token with request headers...

Here Exception is : The provided anti-forgery token was meant for user "", but the current user is "UserName".

I have tried with answer of here Anti forgery token is meant for user "" but the current user is "username" with 3rd solution but can not succeed..

please any one help me how to achieve first 2 steps as per above answer given for it...

or any other solution please let me know...

//view

<script type="text/javascript">

    var JsTokenHeaderValue = '@Utils.TokenHeaderValue()';

</script>

//Antivalidationforgery token:

private Task<HttpResponseMessage> ValidateAntiForgeryToken(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            try
            {
                string cookieToken = "";
                string formToken = "";
                IEnumerable<string> tokenHeaders;
                if (actionContext.Request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
                {
                    string[] tokens = tokenHeaders.First().Split(':');
                    if (tokens.Length == 2)
                    {
                        cookieToken = tokens[0].Trim();
                        formToken = tokens[1].Trim();
                    }
                }
                AntiForgery.Validate(cookieToken, formToken);
            }
            catch (System.Web.Mvc.HttpAntiForgeryException exception)
            {

                ErrorLogDA.LogException(exception);

                actionContext.Response = new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.BadRequest,
                    RequestMessage = actionContext.ControllerContext.Request
                };
                return FromResult(actionContext.Response);
            }
            return continuation();
        }

I am updating my question here the token is due to Membership class, User getting Authenticated without login.. In my case first time i am doing page load then Cookies getting value null and second time page load cookies getting the values from some where .ASPXAUTH .. thats why token issue might be.. here is my controller method for header..

//Header Partial - controller

 public ActionResult UCHeader()
        {
            try
            {

                var ViewLogOnModel = new LogOnModel();

                HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null)
                {
                    ViewLogOnModel.LoggedInUserId = Guid.Empty;
                    return PartialView("UCHeader", ViewLogOnModel);
                }

                //Is Authenticated..
                if (User.Identity.IsAuthenticated == true)
                {
                    if (User.Identity.AuthenticationType == "Forms")
                    {
                        MembershipUser memberUser = Common.Utils.GetLoggedinUserInfo(this.User.Identity.Name);

                        if (memberUser != null)
                        {
                            Guid userId = (Guid)memberUser.ProviderUserKey;

                            ViewLogOnModel.LoggedInUserId = userId;

                            ViewLogOnModel.UserEmail = this.User.Identity.Name;

                            return PartialView("UCHeader", ViewLogOnModel);
                        }
                        else
                        {

                            ViewLogOnModel.LoggedInUserId = Guid.Empty;
                            return PartialView("UCHeader", ViewLogOnModel);
                        }
                    }
                    else
                    {

                        ViewLogOnModel.LoggedInUserId = Guid.Empty;
                        return PartialView("UCHeader", ViewLogOnModel);
                    }

                }
                else
                {

                    ViewLogOnModel.LoggedInUserId = Guid.Empty;
                    return PartialView("UCHeader", ViewLogOnModel);
                }


            }
            catch (Exception ex)
            {
                ErrorLogDA.LogException(ex);
                Response.Redirect("~/ErrorUiLog/Index", false);
            }

            return null;
        }
Community
  • 1
  • 1
  • stackover flow team, pelase reply asap. – user2824057 Oct 01 '13 at 16:39
  • I have seen this error on occasion with our program but it is always when the user credentials are lost in the code. We have to refresh the page or re run the project and the error goes away. I would look into that, maybe add a check for credentials and redirect to login page if lost (if your error is the same as mine). good luck – Matt Bodily Oct 01 '13 at 17:02
  • @Matt : I have login panel in my header of the page and first i am loading the page and added debug point then memberUser is null but i am again doing ...page refresh then memberUser is with user name not null without login, might be that issue, how it is possible that memberuser is getting user name without login.. is there any thing extraa need to do. i think that issue with Antiforgery token.. – user2824057 Oct 01 '13 at 17:28
  • without seeing your code I am not sure, put a break point in your login code and see if you can track where the login information is coming from that is allowing the login on refresh. – Matt Bodily Oct 01 '13 at 17:34
  • @Matt.. ok np.. I have checked with putting debug point but can not figure our why Useris authenticated true and why FormsAuthenticationcookie getting values from some where.. first time page load cookie is null and User Authentication is false.. 2nd time page load cookies gets the values... I am updating my question and putting controller of header for partial view.. – user2824057 Oct 01 '13 at 18:36
  • @Matt :Issue solved it is due to setcookies in one method without login thats why causes the issue of antivalidation forgery token related... – user2824057 Oct 01 '13 at 19:08
  • glad you got it sorted out – Matt Bodily Oct 01 '13 at 19:17
  • Thanks for your help:) – user2824057 Oct 01 '13 at 20:13
  • Please any who will see the post and have problem with mentioned in my question title, so please take care that never set the cookies before login... and if you set cookies by mistake at any place before login then antivalidation forgery token it is considering different token for logged users not for annonumous. – user2824057 Oct 01 '13 at 22:18

0 Answers0