/// <summary> /// Creates a Base64-encoded ticket based on the provided data. /// </summary> /// <param name="ticketData">Data used to create the ticket.</param> /// <param name="secret">Secret key used to create the ticket.</param> /// <param name="encode">True if the user id, user data, and tokens are to be encoded; false otherwise</param> /// <returns>String ticket</returns> /// <remarks>The ticket is created using the mod_auth_tkt algorithm.</remarks> public static string Create(AuthenticationTicketData ticketData, string secret, bool encode = false) { if (ticketData == null) { return(null); } string digest = CreateDigest(ticketData, secret); string userId = (encode) ? Encode(ticketData.UserId, secret, ticketData.UnixTimeStamp, 0) : ticketData.UserId; string tokens = (encode) ? Encode(ticketData.TokensAsString, secret, ticketData.UnixTimeStamp, 4) : ticketData.TokensAsString; string userData = (encode) ? Encode(ticketData.UserData, secret, ticketData.UnixTimeStamp, 8) : ticketData.UserData; string ticket = digest + ticketData.HexTimeStamp + userId + '!'; ticket += (string.IsNullOrEmpty(tokens)) ? userData : tokens + '!' + userData; return(Base64Helper.Encode(ticket)); }
/// <summary> /// Extracts the data from a provided ticket. /// </summary> /// <param name="ticket">Base64-encoded ticket to parse for data</param> /// <param name="secret">Secret key used to create the ticket</param> /// <param name="encoded">True if the user id, user data, and tokens are encoded; false otherwise</param> /// <param name="ipAddress">IP Address used to create the ticket</param> /// <returns>AuthenticationTicketData instance containing the parsed ticket data.</returns> public static AuthenticationTicketData ExtractData(string ticket, string secret = null, bool encoded = false, string ipAddress = AuthenticationTicketData.DefaultIPAddress) { if (string.IsNullOrWhiteSpace(ticket)) { return(null); } if (string.IsNullOrWhiteSpace(secret)) { secret = DefaultSecret; } AuthenticationTicketData ticketData = null; ticket = Base64Helper.DecodeToString(ticket); if (!string.IsNullOrWhiteSpace(ticket) && ticket.Length >= 40) { ticketData = Parse(ticket); if (ticketData != null) { ticketData.IPAddress = ipAddress; if (encoded) { ticketData.UserId = Decode(ticketData.UserId, secret, ticketData.UnixTimeStamp, 0); ticketData.TokensAsString = Decode(ticketData.TokensAsString, secret, ticketData.UnixTimeStamp, 4); ticketData.UserData = Decode(ticketData.UserData, secret, ticketData.UnixTimeStamp, 8); } } } return(ticketData); }