We are planning on using ASP.Net MVC3 to create a JSON API. For handling security we will have something like an API key, or possibly the Username/Password and maybe a timestamp.
I haven't done any MVC before but I'm wondering if there isn't some simple way to add code to Global.asax that ensures that ALL requests have these variables in them somehow. That way, no request could even get through unless it included the API key.
That way we don't have to add API key handling to each section of the site.
Asked
Active
Viewed 213 times
0

James P. Wright
- 8,991
- 23
- 79
- 142
1 Answers
1
Create a global authorization filter -
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class MyAuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
// do Authorization
}
}
then register it in Global.asax -
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyAuthorizationFilterAttribute());
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Although you could create a bespoke Authentication module -
public class CustomAuthentication : IHttpModule
{
public void Init(HttpApplication application)
{
application.AuthenticateRequest += new EventHandler(this.Authenticate);
}
public void Authenticate(object source, EventArgs eventArgs)
{
HttpApplication _application = (HttpApplication)source;
HttpContext _context = _application.Context;
// do authentication
// if authenticated set pricipal
// _context.User = new GenericPrincipal(new GenericIdentity("user"), new string[]);
}
public void Dispose() { }
}
Then you just need to register the module in web.config
<modules runAllManagedModulesForAllRequests="true">
<add name="CustomAuthentication" type="AuthenticationNamespace.CustomAuthentication"/>
</modules>
and set asp.net authentication to none -
<authentication mode="None">
</authentication>
Then you can check to see it the user is authenticated in your AuthorizationFilter.
if(HttpContext.Current.Request.User.Identity.IsAuthenticated)

Duncan Gravill
- 4,552
- 7
- 34
- 51