// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.AspNet.Antiforgery; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.OptionsModel; namespace AntiforgerySample { public class FormPostSampleMiddleware { private readonly Antiforgery _antiforgery; private readonly AntiforgeryOptions _options; private readonly RequestDelegate _next; public FormPostSampleMiddleware( RequestDelegate next, Antiforgery antiforgery, IOptions options) { _next = next; _antiforgery = antiforgery; _options = options.Options; } public async Task Invoke(HttpContext context) { if (context.Request.Method == "GET") { var page = @"
"; var tokenSet = _antiforgery.GetTokens(context, oldCookieToken: null); context.Response.Cookies.Delete(_options.CookieName); context.Response.Cookies.Append(_options.CookieName, tokenSet.CookieToken); await context.Response.WriteAsync(string.Format(page, _options.FormFieldName, tokenSet.FormToken)); } else if (context.Request.Method == "POST") { // This will throw if invalid. await _antiforgery.ValidateAsync(context); var page = @"

Everything is fine

"; await context.Response.WriteAsync(page); } else { await _next(context); } } } }