As seen on visualstudiomagazine.com.
The Encrypted Token Pattern is a defence mechanism against Cross Site Request Forgery (CSRF) attacks, and is an alternative to its sister-patterns; Synchroniser Token, and Double Submit Cookie. The ARMOR Web Framework provides a means to leverage this technique in repelling CSRF attacks against ASP.NET applications.
Click here for an in-depth tutorial on protecting ASP.NET applications from CSRF attacks using this framework.
PM> Install-Package Daishi.Armor.WebFramework
ARMOR requires both encryption and hashing keys, in Base64 format. You can generate both keys using the code below.
Note: Key-generation, rotation, and management are out-of-band topics in terms of leveraging ARMOR.
byte[] encryptionKey = new byte[32];
byte[] hashingKey = new byte[32];
using (var provider = new RNGCryptoServiceProvider()) {
provider.GetBytes(encryptionKey);
provider.GetBytes(hashingKey);
}
Add the following filter to ASP.NET Web API applications
config.Filters.Add(new WebApiArmorFortifyFilter());
Add the following filter to ASP.NET MVC applications
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new MvcArmorFortifyFilter());
}
Add the following attribute to ASP.NET Web API endpoints
[WebApiArmorAuthorize]
Add the following attribute to ASP.NET MVC endpoints
[MvcArmorAuthorize]
Assuming that your application leverages Claims-based authentication, ARMOR will automatically read the UserID claim as follows:
public override bool TryRead(out IEnumerable<Claim> identity) {
var claims = new List<Claim>();
identity = claims;
var claimsIdentity = principal.Identity as ClaimsIdentity;
if (claimsIdentity == null) return false;
var subClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type.Equals(“UserId”));
if (subClaim == null) return false;
claims.Add(subClaim);
return true;
}
If your application leverages any other form of authentication mechanism, simply create your own implementation of IdentityReader
and override the TryRead
method appropriately in order to return the logged-in UserID in Claim-based format.
Please reach out and contact me for questions, suggestions, or to just talk tech in general.