Don't like ads? PRO users don't see any ads ;-)
Guest

ValidateAntiForgeryTokenWrapperAttribute

By: andrew4582 on Oct 18th, 2011  |  syntax: C#  |  size: 1.62 KB  |  hits: 125  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6.  
  7. namespace System.Web.Mvc {
  8.  
  9.     /// <summary>
  10.     /// Wraps <see cref="ValidateAntiForgeryToken"/> to allow attribute to be placed once on the controller class instead on each specific post action
  11.     /// </summary>
  12.     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,AllowMultiple = false,Inherited = true)]
  13.     public class ValidateAntiForgeryTokenWrapperAttribute:FilterAttribute,IAuthorizationFilter {
  14.         private readonly ValidateAntiForgeryTokenAttribute _validator;
  15.  
  16.         public AcceptVerbsAttribute Verbs { get; set; }
  17.         public string Salt { get; set; }
  18.  
  19.         public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs)
  20.             : this(verbs,null) {
  21.         }
  22.  
  23.         public ValidateAntiForgeryTokenWrapperAttribute(string salt)
  24.             : this(HttpVerbs.Post,salt) {
  25.         }
  26.  
  27.         public ValidateAntiForgeryTokenWrapperAttribute(HttpVerbs verbs,string salt) {
  28.  
  29.             this.Verbs = new AcceptVerbsAttribute(verbs);
  30.             this.Salt = salt;
  31.             this._validator = new ValidateAntiForgeryTokenAttribute() {
  32.                 Salt = salt
  33.             };
  34.         }
  35.  
  36.         public void OnAuthorization(AuthorizationContext filterContext) {
  37.  
  38.             string httpMethodOverride = filterContext.HttpContext.Request.GetHttpMethodOverride();
  39.  
  40.             if(this.Verbs.Verbs.Contains(httpMethodOverride,StringComparer.OrdinalIgnoreCase)) {
  41.                 this._validator.OnAuthorization(filterContext);
  42.             }
  43.         }
  44.     }
  45. }