C# ASP.NET MVC安全快速入门

C# ASP.NET MVC安全快速入门,c#,asp.net-mvc,security,C#,Asp.net Mvc,Security,MVC新手问题:我已经启动并运行了我的项目,并且一切正常。现在我想开始限制对某些视图甚至整个控制器的访问。我知道VS 2010软件包附带了一个标准的内置安全模块,包括一个小的压缩包数据库,它可以为您存储用户名和密码,以免-天方夜谭您使用非标准方法 嗯,我不想使用内置的安全性。我有自己的用户表,我自己知道如何加密密码,非常感谢。我想做的就是拥有一个登录方法,如果我确定登录成功,那么我想将会话设置为已验证,并允许用户访问受限视图。应该不会太难吧 我在谷歌上搜索过MVC安全性;问题不在于缺少信息,而在

MVC新手问题:我已经启动并运行了我的项目,并且一切正常。现在我想开始限制对某些视图甚至整个控制器的访问。我知道VS 2010软件包附带了一个标准的内置安全模块,包括一个小的压缩包数据库,它可以为您存储用户名和密码,以免-天方夜谭您使用非标准方法

嗯,我不想使用内置的安全性。我有自己的用户表,我自己知道如何加密密码,非常感谢。我想做的就是拥有一个登录方法,如果我确定登录成功,那么我想将会话设置为已验证,并允许用户访问受限视图。应该不会太难吧


我在谷歌上搜索过MVC安全性;问题不在于缺少信息,而在于信息太多。。。所以,如果有人能直接从我的个人
中删除我的记忆异常
,给我一个适合我的情况的“快速开始”,我真的很感激…

试试这段代码作为指导,我们用它来使用我们自己的模型和数据库登录和注销用户。IdentitySession类可在控制器中用于获取已登录的用户数据。我试图通过在这里删减一些代码来简化我们的代码,所以请不要期望它只是运行。希望能有帮助

public ActionResult Login(int pageId) {
  ViewData["ReturnUrl"] = Request["ReturnUrl"];
  return View(Cms3Configuration.DefaultViewModelWithPage(attachedPage));
}

public ActionResult Process(int pageId, string login, string password, string ReturnUrl) {
  var user = userRepository.GetByUserName(login);
  ViewData["ReturnUrl"] = ReturnUrl;
  if (user != null && authenticator.VerifyAccount(user, password)) {
    authenticator.SignIn(user);
    if (ReturnUrl.IsNotEmpty()) {
      return Redirect(ReturnUrl);
    }
    return Redirect("~" + attachedPage.Parent.Url);
  }
  ////login failed
  TempData[TempDataKeys.Error] = "Invalid login";
  return RedirectToAction("Login", new { pageId = pageId, ReturnUrl });
}

public ActionResult Logout(int pageId) {
  authenticator.SignOut();
  return RedirectToAction<LoginController>(x => x.Login(pageId), new {pageId = pageId});
}

public interface IAuthenticator {
  void SignIn(User person);
  IIdentity GetActiveIdentity();
  WindowsPrincipal GetActiveUser();
  void SignOut();
  bool VerifyAccount(User person, string password);
  bool HasRole(string person, string role);
}

public class Authenticator : IAuthenticator {
  private readonly IHttpContextProvider _httpContextProvider;
  private readonly ICryptographer _cryptographer;
  private readonly IRepository repository;

  public Authenticator(IHttpContextProvider httpContextProvider, ICryptographer cryptographer, IRepository repository) {
    _cryptographer = cryptographer;
    this.repository = repository;
    _httpContextProvider = httpContextProvider;
  }

  public void SignIn(User user) {
    FormsAuthentication.SignOut();
    if (user == null)
      return;
    DateTime issued = DateTime.Now;
    DateTime expires = issued.AddMinutes(30);
    if (user.ExpiryDate.HasValue) {
      if (user.Expires && expires > user.ExpiryDate)
        expires = (DateTime) user.ExpiryDate;
    }
    var roles = user.Roles.Select(x => x.Name).ToList();
    var ticket = new FormsAuthenticationTicket(1, user.UserName, issued, expires, false, string.Join(",", roles.Distinct().ToArray()));
    var encryptedTicket = FormsAuthentication.Encrypt(ticket);
    var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = ticket.Expiration };
    _httpContextProvider.GetCurrentHttpContext().Response.Cookies.Add(authCookie);
  }

  public IIdentity GetActiveIdentity() {
    var httpcontext = _httpContextProvider.GetCurrentHttpContext();
    if (httpcontext == null || httpcontext.User == null)
      return null;
    return httpcontext.User.Identity;
  }

  public WindowsPrincipal GetActiveUser() {
    return _httpContextProvider.GetCurrentHttpContext().User as WindowsPrincipal;
  }

  public void SignOut() {
    FormsAuthentication.SignOut();
  }

  public bool VerifyAccount(User person, string password) {
    string passwordHash = _cryptographer.HashPassword(password, person.PasswordSalt);
    return passwordHash == person.Password && !person.HasExpired() && person.Approved == true;
  }

}

public interface IIdentitySession<T> {
  T GetLoggedInIdentity();
  bool IsAuthenticated { get; }
  bool IsAdministrator { get; }
}

public class IdentitySession<T> : IIdentitySession<T> where T : Identity {
  private readonly IAuthenticator<T> authenticator;
  private readonly IRepository repository;
  private readonly IHttpContextProvider httpContextProvider;
  private T currentIdentity;
  private static readonly object _lock = new object();

  public IdentitySession(IAuthenticator<T> authenticator, IRepository repository,
                         IHttpContextProvider httpContextProvider) {
    this.authenticator = authenticator;
    this.activeDirectoryMapper = activeDirectoryMapper;
    this.repository = repository;
    this.httpContextProvider = httpContextProvider;
  }

  public virtual T GetLoggedInIdentity() {
    IIdentity identity = authenticator.GetActiveIdentity();

    if (identity == null)
      return null;

    if (!identity.IsAuthenticated) 
      return null;

    lock (_lock) {
      if (currentIdentity == null) {
        currentIdentity = repository.Query<T>().Where(x => x.UserName == identity.Name).FirstOrDefault();
      }
    }

    return currentIdentity;
  }

  public bool IsAuthenticated {
    get { return httpContextProvider.GetCurrentHttpContext().User.Identity.IsAuthenticated; }
  }

  public bool IsAdministrator {
    get { return false; }
  }
}
public ActionResult登录(int-pageId){
ViewData[“ReturnUrl”]=请求[“ReturnUrl”];
返回视图(Cms3Configuration.DefaultViewModelWithPage(附件页));
}
公共ActionResult进程(int pageId、字符串登录、字符串密码、字符串返回URL){
var user=userRepository.GetByUserName(登录名);
ViewData[“ReturnUrl”]=ReturnUrl;
if(user!=null&&authenticator.VerifyAccount(user,password)){
验证者签名(用户);
if(ReturnUrl.IsNotEmpty()){
返回重定向(ReturnUrl);
}
返回重定向(“~”+attachedPage.Parent.Url);
}
////登录失败
TempData[TempDataKeys.Error]=“无效登录”;
return RedirectToAction(“Login”,new{pageId=pageId,ReturnUrl});
}
公共操作结果注销(int pageId){
authenticator.SignOut();
返回RedirectToAction(x=>x.Login(pageId),新的{pageId=pageId});
}
公共接口身份验证程序{
无效签名(用户);
IIdentity GetActiveIdentity();
WindowsPrincipal GetActiveUser();
无效签出();
bool VerifyAccount(用户个人、字符串密码);
bool HasRole(字符串人,字符串角色);
}
公共类身份验证程序:IAAuthenticator{
私有只读IHttpContextProvider\u httpContextProvider;
私人只读ICryptographer_加密程序;
私有只读存储库;
公共身份验证器(IHttpContextProvider httpContextProvider、ICryptographer加密程序、IRepository存储库){
_密码学家=密码学家;
this.repository=存储库;
_httpContextProvider=httpContextProvider;
}
公共无效登录(用户){
FormsAuthentication.SignOut();
if(user==null)
返回;
已发布日期时间=DateTime.Now;
DateTime expires=已发布。添加分钟数(30);
if(user.ExpiryDate.HasValue){
if(user.Expires&&Expires>user.expireydate)
expires=(DateTime)user.expireydate;
}
var roles=user.roles.Select(x=>x.Name.ToList();
var ticket=new FormsAuthenticationTicket(1,user.UserName,issued,expires,false,string.Join(“,”,roles.Distinct().ToArray());
var encryptedTicket=FormsAuthentication.Encrypt(票据);
var authCookie=newhttpcookie(FormsAuthentication.formscookeName,encryptedTicket){Expires=ticket.expirement};
_httpContextProvider.GetCurrentHttpContext().Response.Cookies.Add(authCookie);
}
公共身份GetActiveIdentity(){
var httpcontext=_httpContextProvider.GetCurrentHttpContext();
if(httpcontext==null | | httpcontext.User==null)
返回null;
返回httpcontext.User.Identity;
}
公共WindowsPrincipal GetActiveUser(){
返回_httpContextProvider.GetCurrentHttpContext().User作为WindowsPrincipal;
}
公共无效签出(){
FormsAuthentication.SignOut();
}
公共bool验证帐户(用户个人,字符串密码){
字符串passwordHash=\u cryptographer.HashPassword(password,person.PasswordSalt);
return passwordHash==person.Password&&!person.HasExpired()&&person.Approved==true;
}
}
公共接口IIdentialSession{
T GetLoggedInIdentity();
布尔已验证{get;}
布尔IsAdministrator{get;}
}
公共类标识会话:IIdentitySession,其中T:Identity{
专用只读IAAuthenticator验证器;
私有只读存储库;
专用只读IHttpContextProvider httpContextProvider;
私人身份;
私有静态只读对象_lock=new object();
公共身份验证(IAAuthenticator authenticator、IRepository repository、,
IHttpContextProvider(httpContextProvider){
this.authenticator=验证器;
this.activeDirectoryMapper=activeDirectoryMapper;
this.repository=存储库;
this.httpContextProvider=httpContextProvider;
}
公共虚拟T GetLoggedInIdentity(){
IIdentity identity=authenticator.GetActiveIdentity();
if(identity==null)
返回null;
如果(!identity.IsAuthenticated)
返回null;
锁{
if(currentIdentity==null){
currentIdentity=repository.Query().Where(x=>x.UserName==identity.Name).FirstOrDefault();
}
}
返回当前标识;
}
公共图书馆已通过认证{
get{return httpContextProvider.GetCurrentHttpContext().User.Identity.IsAuthenticated;}
}
公共图书馆管理员{
获取{return false;}
}
}

ASP.NET的优点之一是它具有很强的可扩展性。是的,身份验证和授权的默认模型是使用ASP.NET提供的成员资格表(在单独的
[System.Security.Permissions.PrincipalPermission(SecurityAction.Demand, Authenticated = true, Role = "Admin")]
public ActionResult Index()
{
....
}