Cleaning up AntiForgery

This commit is contained in:
ianhong 2015-03-13 09:46:37 -07:00
parent 403f7c7585
commit 29909e15f3
2 changed files with 29 additions and 23 deletions

View File

@ -2,7 +2,6 @@
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc;
using Microsoft.Framework.DependencyInjection;
using MusicStore.Models; using MusicStore.Models;
using MusicStore.ViewModels; using MusicStore.ViewModels;
@ -13,6 +12,9 @@ namespace MusicStore.Controllers
[FromServices] [FromServices]
public MusicStoreContext DbContext { get; set; } public MusicStoreContext DbContext { get; set; }
[FromServices]
public AntiForgery AntiForgery { get; set; }
// //
// GET: /ShoppingCart/ // GET: /ShoppingCart/
public async Task<IActionResult> Index() public async Task<IActionResult> Index()
@ -55,15 +57,14 @@ namespace MusicStore.Controllers
[HttpPost] [HttpPost]
public async Task<IActionResult> RemoveFromCart(int id, CancellationToken requestAborted) public async Task<IActionResult> RemoveFromCart(int id, CancellationToken requestAborted)
{ {
var formParameters = await Context.Request.ReadFormAsync(); var cookieToken = string.Empty;
var requestVerification = formParameters["RequestVerificationToken"]; string formToken = string.Empty;
string cookieToken = null; string[] tokenHeaders = null;
string formToken = null; string[] tokens = null;
if (!string.IsNullOrWhiteSpace(requestVerification)) if (Context.Request.Headers.TryGetValue("RequestVerificationToken", out tokenHeaders))
{ {
var tokens = requestVerification.Split(':'); tokens = tokenHeaders.First().Split(':');
if (tokens != null && tokens.Length == 2) if (tokens != null && tokens.Length == 2)
{ {
cookieToken = tokens[0]; cookieToken = tokens[0];
@ -71,8 +72,7 @@ namespace MusicStore.Controllers
} }
} }
var antiForgery = Context.RequestServices.GetService<AntiForgery>(); AntiForgery.Validate(Context, new AntiForgeryTokenSet(formToken, cookieToken));
antiForgery.Validate(Context, new AntiForgeryTokenSet(formToken, cookieToken));
// Retrieve the current user's shopping cart // Retrieve the current user's shopping cart
var cart = ShoppingCart.GetCart(DbContext, Context); var cart = ShoppingCart.GetCart(DbContext, Context);

View File

@ -24,8 +24,14 @@
if (recordToDelete != '') { if (recordToDelete != '') {
// Perform the ajax post // Perform the ajax post
$.post(PostToUrl, { "id": recordToDelete, "RequestVerificationToken": '@GetAntiXsrfToken()' }, $.ajax(PostToUrl, {
function (data) { type: "post",
data: { "id": recordToDelete },
dataType: "json",
headers: {
"RequestVerificationToken": '@GetAntiXsrfToken()'
}
}).done(function (data) {
// Successful requests get here // Successful requests get here
// Update the page elements // Update the page elements
if (data.ItemCount == 0) { if (data.ItemCount == 0) {