Very simple single user login in ASP.NET MVC2?

2019-05-10 09:22发布

问题:

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?

回答1:

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.



回答2:

Its worth building a light-weight Membership Provider with minimal implementation; GetUser, ValidateUser etc methods. YOu dont need to implement the whole thing. It just helps with authorising pages and checking User.Identity etc when needed. You also dont need the RoleProvider or ProfileProvider to do this.

Its also scalable for the future.

UPDATE

You just need to implement the core methods to valudate and get the user and insert your own validation/data access code.

Something like this....

web.config settings:

<membership defaultProvider="ApplicationMembershipProvider">
      <providers>
        <clear/>
        <add name="ApplicationMembershipProvider" type="YourNamespace.ApplicationMembershipProvider"/>
      </providers>
    </membership>

Login Code:

if (Membership.ValidateUser(username, password))
            {
                FormsAuthentication.SetAuthCookie(username, false);
}


回答3:

You can set the status (logged in or not) in a session variable. Set the variable to true if the user entered the correct password, then on every page you want to restrict access, check if the variable is true.



回答4:

@KristianB a while ago I gave an answer to this SO question. I believe it may be useful since it's very straightforward to implement and at the same time it's better than hardcoding a username and a password in your code.

Good luck!