Created
July 9, 2012 05:26
-
-
Save Daniel15/3074365 to your computer and use it in GitHub Desktop.
Validating JSONP callback function name in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Validation of JSONP callback function names | |
/// </summary> | |
/// <remarks> | |
/// Based off the PHP code at https://gist.github.com/1217080, which is originally based off | |
/// a blog post at http://tav.espians.com/sanitising-jsonp-callback-identifiers-for-security.html | |
/// </remarks> | |
public class JsonValidator | |
{ | |
/// <summary> | |
/// Reserved words in JavaScript - These can't be used in callback function names | |
/// </summary> | |
private static readonly HashSet<string> _reservedWords = new HashSet<string> | |
{ | |
"break", "do", "instanceof", "typeof", "case", "else", "new", "var", "catch", "finally", | |
"return", "void", "continue", "for", "switch", "while", "debugger", "function", "this", | |
"with", "default", "if", "throw", "delete", "in", "try", "class", "enum", "extends", | |
"super", "const", "export", "import", "implements", "let", "private", "public", "yield", | |
"interface", "package", "protected", "static", "null", "true", "false" | |
}; | |
/// <summary> | |
/// Regular expression that all callback function names are validated against | |
/// </summary> | |
private static readonly Regex _validationRegex = new Regex(@"^[a-zA-Z_$][0-9a-zA-Z_$]*(?:\[(?:"".+""|\'.+\'|\d+)\])*?$", RegexOptions.Compiled); | |
/// <summary> | |
/// Validates that the callback function name is valid | |
/// </summary> | |
/// <param name="functionName">Name of the function.</param> | |
/// <returns></returns> | |
public static bool ValidateCallbackFunction(string functionName) | |
{ | |
// Ensure each segment matches the regex, and isn't in the reserved words list. | |
return functionName.Split('.').All(segment => _validationRegex.IsMatch(segment) && !_reservedWords.Contains(segment)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@braco It splits by
.
and then checks every segment individually, so will allowfoo.bar
.