Tuesday, February 18, 2014

Preventing XSRF attacks in Angular with ASP.NET MVC

This is not an easy problem to solve. First, you need to follow this link to implement the overall solution with tokens:


The problem comes with Angular and an application that supports login/logout. That's because the Angular router only requests the templates/pages once, which means the token is only downloaded once (subsequent requests will come from cache). In our scenario, a user could access the application with different accounts, which meant that while the browser was opened, only one token existed and this was causing errors (because different users must have different tokens, otherwise this is considered an XSRF attack). Long story short, the solution was to request the token after the user signed in by causing a page refresh.

This is probably not the best solution, but the alternative was to request the token from the controllers, which would require significant changes and pollution in your classes.

Monday, February 17, 2014

Reading resx programmatically and avoid compiling it with the code

Usually I would be against having a Resources.resx file in production code. It would be better to compile it or put the resources in a database. However, if you need to read the contents in a web project, you could do something like this (from http://msdn.microsoft.com/en-us/library/gg418542(v=vs.110).aspx):

string resxFile = HttpContext.Current.Server.MapPath(@"/CarResources.resx");
      List<Automobile> autos = new List<Automobile>();
      SortedList headers = new SortedList();

      using (ResXResourceReader resxReader = new ResXResourceReader(resxFile))
         foreach (DictionaryEntry entry in resxReader) {
            if (((string) entry.Key).StartsWith("EarlyAuto"))
               autos.Add((Automobile) entry.Value); 
            else if (((string) entry.Key).StartsWith("Header")) 
               headers.Add((string) entry.Key, (string) entry.Value);