我正在构建我的网站,我想限制我网站的一部分(管理部分)正常公开显示。
- 我正在使用 LINQ 进行数据库访问。
- 我有一个服务类来处理通过 LINQ 对数据库的调用
- 我有整个网站运行,除了登录部分。
到目前为止,我只能找到使用 MembershipProvider 和/或 RoleProviders 等的示例。老实说,对于我想要的东西来说,这似乎工作太多了。如果您在输入字段中输入正确的密码,这一切所要做的就是让您进入。
我真的不能避免提供者吗?
我正在构建我的网站,我想限制我网站的一部分(管理部分)正常公开显示。
到目前为止,我只能找到使用 MembershipProvider 和/或 RoleProviders 等的示例。老实说,对于我想要的东西来说,这似乎工作太多了。如果您在输入字段中输入正确的密码,这一切所要做的就是让您进入。
我真的不能避免提供者吗?
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.
构建一个实现最少的轻量级 Membership Provider 是值得的;GetUser、ValidateUser 等方法。你不需要实现整个事情。它只是在需要时帮助授权页面和检查 User.Identity 等。您也不需要 RoleProvider 或 ProfileProvider 来执行此操作。
它还可以为未来扩展。
更新
您只需要实现核心方法来评估和获取用户并插入您自己的验证/数据访问代码。
像这样的东西......
web.config 设置:
<membership defaultProvider="ApplicationMembershipProvider">
<providers>
<clear/>
<add name="ApplicationMembershipProvider" type="YourNamespace.ApplicationMembershipProvider"/>
</providers>
</membership>
登录代码:
if (Membership.ValidateUser(username, password))
{
FormsAuthentication.SetAuthCookie(username, false);
}
您可以在会话变量中设置状态(登录或未登录)。如果用户输入了正确的密码,则将变量设置为 true,然后在要限制访问的每个页面上检查变量是否为 true。
@KristianB 不久前我回答了这个 SO question。我相信它可能很有用,因为它实现起来非常简单,同时它比在代码中硬编码用户名和密码更好。
祝你好运!