Реализация IPrincipal и IIdentity в MVC с использованием настраиваемого поставщика членства и ролей

Я застрял с реализацией настраиваемого объекта iprincpal и iidentity. Я трачу день на поиски того, как реализовать эти права и расширить его дополнительной информацией.

Я хочу расширить информацию (скрытую) с помощью пользовательских переменных, таких как полное имя или что-то еще.

EDIT : Теперь У меня есть следующий код, но если я попытаюсь прочитать (скрыто), я получаю сообщение об ошибке, что System.Web.Security.FormsIdentity не может быть преобразовано в CustomPrincipal .

Есть идеи?

public class CustomPrincipal : GenericPrincipal
{
    public CustomPrincipal(IIdentity identity, String[] roles) : base(identity, roles){ 

    }
    public String Vorname { get; set; }
    public String Nachname { get; set; } 
}

AccountModel:

public class FormsAuthenticationService : IFormsAuthenticationService
{
    public void SignIn(string userName, bool createPersistentCookie)
    {
        if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Der Wert darf nicht NULL oder leer sein.", "userName");
        // Grab user information to insert
        KIMembershipUser membershipUser = (KIMembershipUser)Membership.GetUser(userName);
        var customInfo = String.Format("{0}|{1}", membershipUser.Vorname, membershipUser.Nachname);
        // Create and encrypt the ticket
        var ticket = new FormsAuthenticationTicket(
            2, // Version number
            userName, // Username
            DateTime.Now, // Issue date
            DateTime.Now.AddMinutes(30), // Expiration date
            createPersistentCookie, // Is it persistent?
            customInfo // User data
        );
        var encTicket = FormsAuthentication.Encrypt(ticket);
        // Store the ticket into a cookie
        var cookie = FormsAuthentication.GetAuthCookie(FormsAuthentication.FormsCookieName,createPersistentCookie);
        cookie.Value = encTicket;
        // Append the cookie to the response
        HttpContext.Current.Response.Cookies.Add(cookie); 

        //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    }

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

global.asax:

    protected void Application_PostAuthenticateRequest(){
        // Collect current security information
        var principal = HttpContext.Current.User as RolePrincipal;
        if (principal == null)
            return;
        var identity = principal.Identity as FormsIdentity;
        if (identity == null)
            return;
        var roles = principal.GetRoles();
        // Extract user data in the authentication ticket
        var customInfo = identity.Ticket.UserData;
        var tokens = customInfo.Split('|');
        // Build a richer principal object
        var CustomPrincipal = new CustomPrincipal(identity, roles){
            Vorname = tokens[0],
            Nachname = tokens[1]
        };
        // Store the new principal in the HttpContext
        HttpContext.Current.User = CustomPrincipal;
    }
5
задан Peter Lillevold 6 October 2014 в 19:41
поделиться