Можем ли мы использовать проверку подлинности cookie, предоставленную MVC 5, без использования ASP.Net Identity? - PullRequest
0 голосов
/ 01 февраля 2019

Я пытаюсь перенести существующее приложение, в котором реализована собственная логика аутентификации и авторизации пользователя.Я начал с .NET MVC, который содержит инфраструктуру идентификации Asp.NET для аутентификации и авторизации.Я знаю, что могу настроить удостоверение Asp.NET для использования моих существующих таблиц.

Но возможно ли использовать проверку подлинности Cookie без удостоверения Asp.NET?Я обнаружил, что это доступно для ядра 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 ссылка

Но я не могу найтиHttpContext.SignInAsync метод для Asp.NET MVC 5. Что-то мне не хватает?

1 Ответ

0 голосов
/ 01 февраля 2019

Я сделал это, реализовав свою собственную личность.Таким образом, легко добавить столько свойств, сколько мне нужно.Ниже приведен пример кода с пользовательским свойством 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;
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...