ASP.NET MVC2中非常简单的单用户登录?

Kri*_*anB 3 asp.net asp.net-mvc asp.net-authorization asp.net-authentication asp.net-mvc-2

我正在构建我的网站,我想限制我的网站的一部分(管理部分)从正常的公共显示.

  • 我正在使用LINQ进行数据库访问.
  • 我有一个Service类来通过LINQ处理对数据库的调用
  • 除登录部分外,我整个站点都在运行.

到目前为止,我只能使用MembershipProvider和/或RoleProviders等找到示例.说实话,它看起来似乎太多了我想要的东西.如果您在输入字段中键入正确的密码,所有这一切都是让您进入.

我真的不能避开提供商吗?

sma*_*man 6

由于您只有一个用户,因此无需创建数据库依赖关系.您可以根据硬编码凭据制作非常简单的授权服务.例如,

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;
     }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以建立一个自定义IAuthorizationFilter:

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

然后你要做的就是装饰受保护的控制器动作,SimpleAuthFilter你的应用程序的登录突然起作用.好极了!(注意,我在StackOverflow应答窗口中写了所有这些代码,所以你可能需要在实际工作之前清理错别字等)

此外,如果您发现不必要,可以重构此操作以省略用户名.如果希望可以访问受保护的控制器操作,则需要为其创建一个控制器操作LoginLogout进行相应的调用AuthorizationService.