身份验证票证中的ASP.Net核心自定义数据

时间:2016-07-18 11:46:43

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

ASP.Net核心保存自定义身份验证票据的最佳做法是什么? 换句话说,如何在MVC 6方面实现以下目标:

    public static void SignIn(string username, bool persistent, long accountId)
    {
        const int version = 1;
        DateTime issue = DateTime.Now;
        DateTime expiration = issue.AddMonths(1);
        string data = accountId.ToString();

        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(version, username, issue, expiration, persistent, data);
        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));

        if (persistent == true)
            cookie.Expires = expiration;

        HttpContext.Current.Response.Cookies.Add(cookie);
    }

1 个答案:

答案 0 :(得分:0)

在使用IApplicationBuilder应用程序的configure方法的Startup类中:

application.CustomCookieAuthentication(login);

根据您自己的代码,需要进行一些调整。根据您的设置,某些类方法也应该由您自己替换。但我认为通常的解决方案是明确的:

public static IApplicationBuilder CustomCookieAuthentication(this IApplicationBuilder application, string url)
{
    if (application == null)
        throw new ArgumentNullException(nameof(application));

    if (url == null)
        throw new ArgumentNullException(nameof(url));

    IApplicationBuilder chain = application.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        CookieName = SecurityExtensions.CookieName,
        CookieHttpOnly = true,
        CookieSecure = Configuration.Authentication.Cookie.Secure,
        ExpireTimeSpan = TimeSpan.FromDays(30),
        SlidingExpiration = true,
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        LoginPath = new PathString(url),
        AccessDeniedPath = new PathString(url)
    });

    return chain;
}

public static async Task Login(this HttpContext context, string username, Unique accountId, bool persistent)
{
    await context.Logout();

    Claim id = new Claim(ClaimTypes.UserData, accountId.ToString());
    Claim version = new Claim(ClaimTypes.Version, SecurityExtensions.Version.ToString());
    ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { id, version }, SecurityExtensions.CookieName));

    DateTime utc = DateTime.UtcNow;

    AuthenticationProperties properties = new AuthenticationProperties();
    properties.IssuedUtc = utc;
    properties.IsPersistent = persistent;

    if (persistent == true)
        properties.ExpiresUtc = utc.AddYears(1);

    await context.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
}

public static async Task Logout(this HttpContext context)
{
    await context.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    ISession session = SecurityExtensions.GetSession(context);
    session?.Clear();
}