Reload AntiForgeryToken after a login

前端 未结 2 1578
感动是毒
感动是毒 2021-01-02 04:48

I need to reload an AntiForgeryToken in a form located in a view, after a successfull login in another view in the same page.

Can I make an update in the form input

2条回答
  •  醉梦人生
    2021-01-02 05:49

    You can achieve this by simply returning the AntiForgeryToken after they log in.

    No need to re-use the same token 2 times.

    Controller:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model)
    {
      // do something with login
      // return new token as a partial to parse and get value
      return this.PartialView("_AntiForgeryPartial");
    }
    

    _AntiForgeryPartial:

    @Html.AntiForgeryToken()
    

    You can use JS similar to this to load ONLY the new AntiForgeryToken value into the comment form.

    View:

    $("#LoginForm").submit(function (e) {
        e.preventDefault();
    
        var $this = $(this);
    
        $.ajax({
            type: $this.attr("method"),
            url: $this.attr("action"),
            data: $this.serialize(),
            success: function (response) {
                // get the new token from the response html
                var val = $(response).find('input[type="hidden"]').val();
                // set the new token value
                $('.commentsform input[type="hidden"]').val(val);
            }
        });
    });
    

    When the comment form does the POST, you should be able to validate against the new unique AntiForgeryToken.

    Steven Sanderson has a great post on the AntiForgeryToken() if you would like to learn more on how to use it and what it's for.

提交回复
热议问题