This repository has been archived by the owner on Dec 14, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
AntiforgeryExtensions.cs
68 lines (61 loc) · 2.62 KB
/
AntiforgeryExtensions.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 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;
using System.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
namespace Microsoft.AspNetCore.Mvc.ViewFeatures
{
public static class AntiforgeryExtensions
{
/// <summary>
/// Generates an <input type="hidden"> element for an antiforgery token.
/// </summary>
/// <param name="antiforgery">The <see cref="IAntiforgery"/> instance.</param>
/// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param>
/// <returns>
/// A <see cref="IHtmlContent"/> containing an <input type="hidden"> element. This element should be put
/// inside a <form>.
/// </returns>
/// <remarks>
/// This method has a side effect:
/// A response cookie is set if there is no valid cookie associated with the request.
/// </remarks>
public static IHtmlContent GetHtml(this IAntiforgery antiforgery, HttpContext httpContext)
{
if (antiforgery == null)
{
throw new ArgumentNullException(nameof(antiforgery));
}
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var tokenSet = antiforgery.GetAndStoreTokens(httpContext);
return new InputContent(tokenSet);
}
private class InputContent : IHtmlContent
{
private readonly string _fieldName;
private readonly string _requestToken;
public InputContent(AntiforgeryTokenSet tokenSet)
{
_fieldName = tokenSet.FormFieldName;
_requestToken = tokenSet.RequestToken;
}
// Though _requestToken normally contains only US-ASCII letters, numbers, '-', and '_', must assume the
// IAntiforgeryTokenSerializer implementation has been overridden. Similarly, users may choose a
// _fieldName containing almost any character.
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
writer.Write("<input name=\"");
encoder.Encode(writer, _fieldName);
writer.Write("\" type=\"hidden\" value=\"");
encoder.Encode(writer, _requestToken);
writer.Write("\" />");
}
}
}
}