n this example, we'll be setting up a custom authorization scheme based on a key which will be validated using a very simple algorithm. This isn't secure for any number of reasons, but with some minor modifications (e.g. expiring a key once it is used) it would be sufficient for things like simple beta program for a pre-release website.
We'll accept a parameter called X-Key and validate that it's a number that passes a simple check.
To start with, we'll create a new class called KeyAuthorizeAttribute that inherits from AuthorizeAttribute:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
public class KeyAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { string key = httpContext.Request[ "X-Key" ]; return ApiValidatorService.IsValid(key); } } public static class ApiValidatorService { public static bool IsValid( string key) { int keyvalue; if ( int .TryParse(key, out keyvalue)) { return keyvalue % 2137 == 7; } return false ; } } |
This AuthorizeCore method checks a value (via header, querystring, form post, etc.) and calls into a service to validate it. In this case, validation is a simple static method that runs our validation algorithm. In your case, you'd probably want to check against a list of pre-issued keys in a database, call out to an external service, etc. AuthorizeCore returns a boolean value - pass or fail.
We can then slap that [KeyAuthorize] attribute on any action or controller in the site, or register it globally (as shown in my previous post).
This request would be allowed: http://localhost:8515/?X-Key=26381272 (because 26381272 mod 2137 equals 7)
This request would be denied: http://localhost:8515/?X-Key=12345