开发与Web表单应用程序一致的自定义身份验证和授权系统

sha*_*wat 4 c# asp.net security asp.net-mvc asp.net-mvc-4

我正在创建一个新的ASP.NET MVC 4应用程序(实际上是我的第一个MVC应用程序),它是我之前的ASP.NET Web窗体应用程序的一部分.我从未在任何项目中使用ASP.NET内置身份验证方法.这个新的MVC 4应用程序将发布在以前的应用程序的子域上.登录将从之前的应用程序完成.如果没有登录,应该从MVC应用程序提供返回URL以返回当前页面.但是,新用户注册,帐户恢复选项已经在以前的Web表单应用程序中开发,我不想在我的新MVC中复制它们应用.

如果token成功登录,将从Web表单应用程序发出带有令牌号的cookie ,该cookie 将被共享给所有域*.maindomain.com.

现在我想将自己的令牌验证方法与ASP.NET内置方法合并,以便我可以Authorize在我的新MVC应用程序中使用和其他安全相关的选项.

在我之前的应用程序中,我以下列方式开发了自定义用户验证系统.

首先,我有以下相关的SQL Server表

在此输入图像描述

和以下课程

public class Token
{
    public static uint GenerateToken(string userEmail, string password, bool isPersistent)
    {
        // this static function generates a uint type unique token number
        // and put this in the cookie "token" using HttpContext.Current.Response object.
        // if isPersistent is set to true then cookie will be persistent otherwise not
        // if there is any problem in creating token then it will throw an Exception with proper message
        // Possible causes of not generating a token are
        // 1. Invalid useremail or password
        // 2. 'State' value in 'Member' table is 'EmailPending' or 'Suspended' (there is an enum for MemberState
    }

    public Token(uint tokenNo, bool validateImmediately = false)
    {
        // simply load token details with a few filed from member table from database
        // Call validate function if validateImmediately is set to true
        // Throws an exception if token does not exists in the database
    }

    public void Validate()
    {
        // Checks for everything like MemberState is Active and Token status is also Active and throws exception if anything wrong
        // and then check (LastAccessedOn.AddSeconds(TokenLife) < AppSettings.Now) is not true
        // Call UpdateStatus function with new token status and current page from HttpContext in comment parameter
    }

    public void UpdateStatus((TokenStatus newStatus, string comment = "")
    {
        // simply write both newStatus and Comment in Token table
        // and remove the token cookie if newStatus is not set to Active
    }

    public uint TokenNumber { get; private set; }
    public uint MemberNumber { get; private set; } // from Member table
    public string Name { get; private set; } // from Member table
    public MemberState MemberState { get; private set; } // from Member table
    public string MemberEmail { get; private set; } // from member table
    public uint BusinsessNo { get; private set; } // from Business table
    public DateTime CreatedOn { get; private set; }
    public DateTime LastAccessedOn { get; private set; }
    public uint TokenLife { get; private set; } // from member
    public string CreatedIP { get; private set; }
    public string LastIP { get; private set; }
    public bool IsPersistent { get; private set; }
    public TokenStatus Status { get; private set; }
    public string Comment { get; private set; }
    public static Token Current
    {
        get
        {
            if (_t == null)
                _t = new Token(uint.Parse(HttpContext.Current.Request.Cookies["token"].Value));
            return _t;
        }
    }
    private static Token _t;
}

public class Member
{
     // all member related operations like new member, send verification email and verify email
}
Run Code Online (Sandbox Code Playgroud)

对于注销用户,我只需调用UpdateStatus (TokenSatus.Closed, "User logged out").此方法将负责删除cookie.

注意:会员类有一个属性bool IsAdmin.你知道它的原因.

请根据我在MVC应用程序中的需求,建议我开发认证系统的最佳解决方案.我再告诉你,选择喜欢的New User,Account Recovery而且Email Verification会在我以前的ASP.NET Web表单应用程序来完成.我只需要将我的Validate()方法Token放在MVC应用程序中的正确位置.我真的很困惑互联网上的几种解决方案.

Win*_*Win 7

如果您手动滚动自己的身份验证,则安全性只能与安全地在客户端cookie中存储Ticket的方式一样强.

通常,您希望加密身份验证票证/令牌并通过SSL进行访问.只要您在客户端安全地存储cookie,就不应该成为问题.

我还想建议看看ASP.Net如何创建表单身份验证票证.

注意:如果使用ASP.Net表单身份验证票证,则无需在数据库中存储票证/令牌,因为用户将在每个页面请求时将auth票证发送到服务器.

var now = DateTime.UtcNow.ToLocalTime();

var ticket = new FormsAuthenticationTicket(
                1, /*version*/
                MemberID,
                now,
                now.Add(FormsAuthentication.Timeout),
                createPersistentCookie,
                TokenID, /*custom data*/
                FormsAuthentication.FormsCookiePath);

var encryptedTicket = FormsAuthentication.Encrypt(ticket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
{
   HttpOnly = true,
   Secure = FormsAuthentication.RequireSSL,
   Path = FormsAuthentication.FormsCookiePath
};

if (ticket.IsPersistent)
{
   cookie.Expires = ticket.Expiration;
}
if (FormsAuthentication.CookieDomain != null)
{
   cookie.Domain = FormsAuthentication.CookieDomain;
}

_httpContext.Response.Cookies.Add(cookie);
Run Code Online (Sandbox Code Playgroud)

如何创建主体对象

一旦为经过身份验证的用户请求了一个页面,您需要从cookie中检索身份验证票证,并创建一个Principal对象.

// In Global.asax.cs
void Application_AuthenticateRequest(object sender, EventArgs e)
{
   HttpCookie decryptedCookie = 
      Context.Request.Cookies[FormsAuthentication.FormsCookieName];

   FormsAuthenticationTicket ticket = 
      FormsAuthentication.Decrypt(decryptedCookie.Value);

   var identity = new GenericIdentity(ticket.Name);
   var principal = new GenericPrincipal(identity, null);

   HttpContext.Current.User = principal;
   Thread.CurrentPrincipal =HttpContext.Current.User;
}

// In action method, how to check whether user is logged in 
if (User.Identity.IsAuthenticated)
{

}
Run Code Online (Sandbox Code Playgroud)

我是否需要延长cookie过期时间?

如果将slidingExpiration保留为true(默认情况下为true),则会自动增加到期时间.(阅读更多文章)