Search code examples
asp.netasp.net-mvcasp.net-mvc-2asp.net-authenticationasp.net-authorization

Very simple single user login in ASP.NET MVC2?


I'm building my site, and I want to restrict a part of my site (The admin parts) from normal public display.

  • I am using LINQ for database access.
  • I have a Service class to handle calls to the database through LINQ
  • I have the whole site running, except for the Login part.

So far I have only been able to find examples using MembershipProvider and/or RoleProviders etc. And to be honest, it does seem like too much work for what I want. All this has to do is to let you in if you type the correct password in the input fields.

Can i really not avoid the Providers?


Solution

  • Since you only have a single user you don't need to create a database dependency. You can make a very simple authorization service based off of a hard coded credentials. For example,

    public class AuthorizationService{
         private AuthorizationService(){}
         public static readonly AuthorizationService Instance = new AuthorizationService();
    
         private const string HardCodedAdminUsername = "someone";
         private const string HardCodedAdminPassword = "secret";
         private readonly string AuthorizationKey = "ADMIN_AUTHORIZATION";
    
         public bool Login(string username, string password, HttpSessionStateBase session){
             if(username.ToLowerInvariant().Trim()==HardCodedAdminUsername && password.ToLowerInvariant().Trim()==HardCodedAdminPassword){
                  session[AuthorizationKey] = true;
                  return true;
             } 
             return false;
         }
    
         public void Logout(HttpSessionStateBase session){
            session[AuthorizationKey] = false;
         }
    
         public bool IsAdmin(HttpSessionStateBase session){
             return session[AuthorizationKey] == true;
         }
    }
    

    Then you can build a custom IAuthorizationFilter like:

    public class SimpleAuthFilterAttribute: FilterAttribute, IAuthorizationFilter{
         public void OnAuthorization(AuthorizationContext filterContext){
             if(!AuthorizationService.Instance.IsAdmin(filterContext.HttpContext.Session)){
                  throw new UnauthorizedAccessException();
             }
         }
    }
    

    Then all you have to do is decorate the protected controller actions with the SimpleAuthFilter and you're application's login suddenly works. Yay! (Note, I wrote all this code in the StackOverflow answer window, so you may need to clean up typos, etc. before it actually works)

    Also, you could refactor this to omit the username if you find that unnecessary. You will need to create a controller action for Login and Logout that make the corresponding calls to the AuthorizationService, if you want your protected controller actions to ever be accessible.