-
Notifications
You must be signed in to change notification settings - Fork 1
/
AngularAntiForgeryTokenAttribute.cs
39 lines (34 loc) · 1.25 KB
/
AngularAntiForgeryTokenAttribute.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
using System;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Filters;
namespace ASPNetCoreAngular2Payments
{
/// <summary>
/// This attribute adds token in Cookie in Response
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class AngularAntiForgeryTokenAttribute: ActionFilterAttribute
{
private const string CookieName = "XSRF-TOKEN";
private readonly IAntiforgery _antiforgery;
public AngularAntiForgeryTokenAttribute(IAntiforgery antiforgery)
{
_antiforgery = antiforgery;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
base.OnResultExecuting(context);
if (context.Cancel) return;
var tokens = _antiforgery.GetAndStoreTokens(context.HttpContext);
context.HttpContext.Response.Cookies.Append(
CookieName,
tokens.RequestToken,
new CookieOptions { HttpOnly = false });
}
}
}