我们可以使用MVC 5提供的cookie身份验证而不使用ASP.Net Identity吗?

时间:2019-02-01 09:55:44

标签: asp.net asp.net-mvc asp.net-core

我正在尝试迁移已实现自己的用户身份验证和授权逻辑的现有应用程序。我从.NET MVC开始,其中包含用于身份验证和授权的Asp.NET身份框架。我知道我可以自定义Asp.NET身份以使用现有表。

但是可以在没有Asp.NET身份的情况下使用Cookie身份验证吗?我发现此代码可用于Asp.NET内核,其代码如下:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, user.Email),
    new Claim("FullName", user.FullName),
    new Claim(ClaimTypes.Role, "Administrator"),
};

var claimsIdentity = new ClaimsIdentity(
    claims, CookieAuthenticationDefaults.AuthenticationScheme);

var authProperties = new AuthenticationProperties
{
    //AllowRefresh = <bool>,
    // Refreshing the authentication session should be allowed.

    //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
    // The time at which the authentication ticket expires. A 
    // value set here overrides the ExpireTimeSpan option of 
    // CookieAuthenticationOptions set with AddCookie.

    //IsPersistent = true,
    // Whether the authentication session is persisted across 
    // multiple requests. Required when setting the 
    // ExpireTimeSpan option of CookieAuthenticationOptions 
    // set with AddCookie. Also required when setting 
    // ExpiresUtc.

    //IssuedUtc = <DateTimeOffset>,
    // The time at which the authentication ticket was issued.

    //RedirectUri = <string>
    // The full path or absolute URI to be used as an http 
    // redirect response value.
};

await HttpContext.SignInAsync(
    CookieAuthenticationDefaults.AuthenticationScheme, 
    new ClaimsPrincipal(claimsIdentity), 
    authProperties);

以上代码取自Microsoft文档link

但是我找不到Asp.NET MVC 5的HttpContext.SignInAsync方法。我缺少什么吗?

1 个答案:

答案 0 :(得分:2)

我通过实现自己的身份来做到这一点。这样,添加所需数量的属性就很容易。下面是具有自定义属性friendlyName的代码示例

public class Identity : IIdentity
    {
        public Identity(int id, string name, string friendlyName, string roles)
        {
            this.ID = id;
            this.Name = name;
            this.FriendlyName = friendlyName;
            this.Roles = roles;
        }



  public Identity(string name, string data)
    {
        if (string.IsNullOrWhiteSpace(data))
            throw new ArgumentException();

        string[] values = data.Split('|');
        if (values.Length != 3)
            throw new ArgumentException();

        this.Name = name;
        this.ID = Convert.ToInt32(values[0]);
        this.FriendlyName = values[1];
        Roles = values[2];
    }

    public string AuthenticationType
    {
        get { return "Custom"; }
    }

    public bool IsAuthenticated
    {
        get { return true; }
    }

    public override string ToString()
    {
        return FriendlyName;
    }

    public string GetUserData()
    {
        return string.Format("{0}|{1}|{2}", ID, FriendlyName, Roles);
    }


    public int ID { get; private set; }
    public string Name { get; private set; }
    public string FriendlyName { get; private set; }
    public string Roles { get; private set; }
}

//in controller on login action:
        Identity id = new Identity(user.ID,  user.Username, "some friendly name", user.Roles);
        DateTime expire = DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes);
        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(id.ID, user.Username, DateTime.Now, expire, false, id.GetUserData());
        string hashTicket = FormsAuthentication.Encrypt(ticket);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
        HttpContext.Response.Cookies.Add(cookie);

在global.asax中,您拥有:

public override void Init()
        {
            base.Init();
            PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
        }

    void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            if (authTicket == null || authTicket.Expired)
                return;

            Identity id = new Identity(authTicket.Name, authTicket.UserData);
            Principal user = new Principal(id);
            Context.User = user;
            Thread.CurrentPrincipal = user;
        }
    }