Skip to content

Instantly share code, notes, and snippets.

@RyanABailey
Last active April 5, 2019 05:10
Show Gist options
  • Select an option

  • Save RyanABailey/6cdfd6fa5bf9529ca48e to your computer and use it in GitHub Desktop.

Select an option

Save RyanABailey/6cdfd6fa5bf9529ca48e to your computer and use it in GitHub Desktop.
CSRF in AngularJS/Web API
app.factory('LoginProvider', function ($resource) {
return $resource('/api/login/:id', { id: '@id' },
{ 'save': { method: 'POST', headers: { 'X-XSRF-Token': angular.element('input[name="__RequestVerificationToken"]').attr('value') } } });
});
app.factory('OtherProvider', function ($resource) {
return $resource('/api/OtherProvider/:id', { id: '@id' },
{'get': { method: 'GET', headers: { 'X-XSRF-Token': angular.element('input[name="__RequestVerificationToken"]').attr('value') } }});
});
using System;
using System.Linq;
using System.Net.Http;
using System.Web.Helpers;
using System.Web.Http.Filters;
namespace Web.Common.AntiForgery
{
public sealed class AntiForgeryTokenAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext == null)
{
throw new ArgumentNullException("actionContext");
}
var headers = actionContext.Request.Headers;
var cookie = headers
.GetCookies()
.Select(c => c[AntiForgeryConfig.CookieName])
.FirstOrDefault();
var tokenFromHeader = headers.GetValues("X-XSRF-Token").FirstOrDefault();
System.Web.Helpers.AntiForgery.Validate(cookie != null ? cookie.Value : null, tokenFromHeader);
base.OnActionExecuting(actionContext);
}
}
}
<%# AntiForgery.GetHtml() %>
namespace Web.Services
{
[RoutePrefix("api/login")]
[Route("{action=Post}")]
public class LoginController : ApiController
{
[AntiForgeryToken]
[ResponseType(typeof(LoginResponseModel))]
[Route("")]
public IHttpActionResult Post([FromBody]LoginRequestModel request)
{
var response = new LoginResponseModel();
// Business Logic
return Ok(response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment