How To Store Custom Data In Membership Cookie
Jul 14, 2010
give me an example (or point me in the right direction) on how to store custom data in an ASP.NET Membership cookie? I need to add some custom properties like UserID and URLSlug to the cookie and be able to retrieve the information in the same way one would retrieve the Username.
Edit:
I used Code Poet's example and came up with the following.
When I set a breakpoint at Dim SerializedUser As String = SerializeUser(userData) the value of userData is right. It has all the properties I expect it to have.
The problem I'm now running into is that when I get to Dim userdata As String = authTicket.UserData (breakpoint), the value is "". I'd love to figure out what I'm doing wrong.
Here's the code.
Imports System
Imports System.Web
Imports System.Web.Security
Namespace Utilities.Authentication
Public NotInheritable Class CustomAuthentication
Private Sub New()
End Sub
Public Shared Function CreateAuthCookie(ByVal userName As String, ByVal userData As Domain.Models.UserSessionModel, ByVal persistent As Boolean) As HttpCookie
Dim issued As DateTime = DateTime.Now
''# formsAuth does not expose timeout!? have to hack around the
''# spoiled parts and keep moving..
Dim fooCookie As HttpCookie = FormsAuthentication.GetAuthCookie("foo", True)
Dim formsTimeout As Integer = Convert.ToInt32((fooCookie.Expires - DateTime.Now).TotalMinutes)
Dim expiration As DateTime = DateTime.Now.AddMinutes(formsTimeout)
Dim cookiePath As String = FormsAuthentication.FormsCookiePath
Dim SerializedUser As String = SerializeUser(userData)
Dim ticket = New FormsAuthenticationTicket(0, userName, issued, expiration, True, SerializedUser, cookiePath)
Return CreateAuthCookie(ticket, expiration, persistent)
End Function
Public Shared Function CreateAuthCookie(ByVal ticket As FormsAuthenticationTicket, ByVal expiration As DateTime, ByVal persistent As Boolean) As HttpCookie
Dim creamyFilling As String = FormsAuthentication.Encrypt(ticket)
Dim cookie = New HttpCookie(FormsAuthentication.FormsCookieName, creamyFilling) With { _
.Domain = FormsAuthentication.CookieDomain, _
.Path = FormsAuthentication.FormsCookiePath _
}
If persistent Then
cookie.Expires = expiration
End If
Return cookie
End Function
Public Shared Function RetrieveAuthUser() As Domain.Models.UserSessionModel
Dim cookieName As String = FormsAuthentication.FormsCookieName
Dim authCookie As HttpCookie = HttpContext.Current.Request.Cookies(cookieName)
Dim authTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
Dim userdata As String = authTicket.UserData
Dim usersessionmodel As New Domain.Models.UserSessionModel
usersessionmodel = DeserializeUser(userdata)
Return usersessionmodel
End Function
Private Shared Function SerializeUser(ByVal usersessionmodel As Domain.Models.UserSessionModel) As String
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim mem As New IO.MemoryStream
bf.Serialize(mem, usersessionmodel)
Return Convert.ToBase64String(mem.ToArray())
End Function
Private Shared Function DeserializeUser(ByVal serializedusersessionmodel As String) As Domain.Models.UserSessionModel
Dim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Dim mem As New IO.MemoryStream(Convert.FromBase64String(serializedusersessionmodel))
Return DirectCast(bf.Deserialize(mem), Domain.Models.UserSessionModel)
End Function
End Class
End Namespace
Here's where I create all the magic. This method is in a "BaseController" class that inherits System.Web.Mvc.Controller
Protected Overrides Function CreateActionInvoker() As System.Web.Mvc.IActionInvoker
If User.Identity.IsAuthenticated Then ''# this if statement will eventually also check to make sure that the cookie actually exists.
Dim sessionuser As Domain.Models.UserSessionModel = New Domain.Models.UserSessionModel(OpenIdService.GetOpenId(HttpContext.User.Identity.Name).User)
HttpContext.Response.Cookies.Add(UrbanNow.Core.Utilities.Authentication.CustomAuthentication.CreateAuthCookie(HttpContext.User.Identity.Name, sessionuser, True))
End If
End Function
And here's how I try and retrieve the info.
Dim user As Domain.Models.UserSessionModel = CustomAuthentication.RetrieveAuthUser
View 2 Replies
Similar Messages:
Nov 12, 2010
i have a custom membership provider and do manual validation of the user when they log in and set a persistent cookie with this bit of code:
FormsAuthentication.RedirectFromLoginPage(this.txtEmail.Text,
this.cbRememberMe.Checked);
The cookie gets set fine. I can tell it has all the data it needs by looking at it in Fiddler once im validated. However coming back to the site im always getting prompted to log in again. I am starting to think the problem isn't how im saving the cookie but that maybe my custom membership isn't acutally looking for this auth cookie again. Or im naming it wrong or something.
Two things
1) My membership provider is custom and NOT added to web.config - it's a .cs file that connects to a CMS back end for the validation and it works fine logging people in and such it just never keeps (or uses) the persistent cookie.
NOTE: the persistence doesn't work anywhere (on my local machine / staging server or live server - Application name is simply "/")
NOTE 2: as an aside we have a google search applicance. Which we baked a 10 year cookie for on this site - we opened up the cookie and used the encrypted string in the google search appliance (this is how you get it to get past logins, etc) and this thing works great- it logs itself in no problem all the time. SO i am a bit lost as to why a user with an almost identical cookie is not getting logged in.
View 1 Replies
Jun 14, 2010
I am a bit baffled here; using IE7, ASP.NET 2.0 and Cassini (the VS built-in web server; although the same thing seems to be true for "real" applications deployed in IIS) I am looking for the session-id-cookie. My test page shows a session id (by printing out Session.SessionId) and Response.Cookies.Keys contains ASP.NET_SessionId. So far so good.
But I cannot find the cookie in IEs cookie-store! Nor does "remove all cookies" reset the session (as it does in FF)... So where - I am tempted to write that four letter word - does IE store that bloody cookie? Or am I missing something? By the way there is no hidden field with a session id either, as far as I can see. If I check in FF there is a cookie called ASP.NET_SessionId as I would expect. And as mentioned above deleting that cookie does start a new session; as I would expect.
View 1 Replies
Aug 12, 2010
I have a custom membership user class and custom MembershipProvider working against database. Due to security reasons the user passwords are stored in the database as hashed values. So my procedure
public override bool ValidateUser(string username, string password) is
{
//select hashed password from db
return (EncodePassword(password) == dbpassword)
}
[code]....
View 4 Replies
Jan 5, 2011
This is my first membership provider; I converted the sample provider [URL] to SQL. I created a vb class provider and put it into the App_Code folder. After it was created I tried to modify my webconfig but the error pops up. I don't know what else to try, I don't know if I have missed something
webconfig:
[code]....
View 1 Replies
Mar 27, 2010
I'm using the ASP.NET SQL Membership Provider. So, there's an aspnet_Users table that has details of each of my users. (Actually, the aspnet_Membership table seems to contain most of the actual data). I now want to store some per-user information in my database, so I thought I'd just create a new table with a UserId (GUID) column and an FK relationship to aspnet_Users. However, I then discovered that I can't easily get access to the UserId since it's not exposed via the membership API. (I know I can access it via the ProviderUserKey, but it seems like the API is abstracting away the internal UserID in favor of the UserName, and I don't want to go too far against the grain).
So, I thought I should instead put a LoweredUserName column in my table, and create an FK relationship to aspnet_Users using that. Bzzzt. Wrong again, because while there is a unique index in aspnet_Users that includes the LoweredUserName, it also includes the ApplicationId - so in order to create my FK relationship, I'd need to have an ApplicationId column in my table too. At first I thought: fine, I'm only dealing with a single application, so I'll just add such a column and give it a default value. Then I realised that the ApplicationId is a GUID, so it'd be a pain to do this. Not hard exactly, but until I roll out my DB I can't predict what the GUID is going to be. I feel like I'm missing something, or going about things the wrong way. What am I supposed to do?
View 3 Replies
Apr 10, 2010
I'm using session to store C# object but my session is expiring regularly.
I've given 540 minutes for session timeout. ( <sessionState mode="InProc" timeout="540"/>)
Now I want to use cookie instead of session to remove this timeout problem.
code below:
[code].....
View 17 Replies
Dec 1, 2010
Can i still store value in session if in browser cookie is disabled?
View 2 Replies
Nov 15, 2010
Using ASP.NET 2.0, with forms authentication.
Just for a test, I configured the roles cookie in web.config like this :
<roleManager enabled="true" cacheRolesInCookie="true" cookieName=".ASPXROLES" cookieTimeout="2"></roleManager>
I wanted to see what would happen when the cached role cookie expired. Using Fiddler, after 2 minutes had elapsed, I could see that the raw value of the role cookie had changed.
I was expecting that on expiry, that ASP.NET would simply re-read the roles information from the database, and repopulate the cookie with the same value. So my question is, why would the raw value of the cookie change after expiry ? The cookie value is not human-readable (base 64 encoded and/or encrypted ?), so I can't tell if the information in it is the same, although the application still seems to work fine.
EDIT :
It looks like each time the roles are encrypted and cached in the cookie, it gets a different raw value.
e.g. if you run the following code :
RolePrincipal rp = (RolePrincipal) User;
string str = rp.ToEncryptedTicket();
Label1.Text = str;
View 1 Replies
Jan 6, 2011
I have an application running ASP.NET. I have different domains and different sub-domains. I want the domains to share session with their sub domains.
For Example, the following domains access this application:
[URL]
If a user goes to www.example1.com and print.example1.com, I want it to use the same session. If the user were to go to www.example2.com and print.example2.com, I would want it to use a different session than the *.example1.com.
The way I used to handle it was a hack in page_load that works perfectly in IIS6:
Response.Cookies["ASP.NET_SessionId"].Value = Session.SessionID;
Response.Cookies["ASP.NET_SessionId"].Domain = SiteUtility.GetCookieDomain();
(SiteUtility.GetCookieDomain would return .example1.com or .example2.com depending on the url of the request) Unfortunately, this no longer seems to work for iis7. Each subdomain/domain a user goes to, the user gets a new session cookie.
I then found the web.config entry: '<httpCookies domain=".example1.com" />. This works great for sharing session cookie between example1.com subdomains. Unfortunately, this completely screws up session state for *.example2.com.
View 3 Replies
Mar 22, 2010
How can I transfer the login session of a user into a Cookie that would expire in 12 hours? I have a problem with Internet Explorer where whenever the user closes the window it would log them out automatically (which is by default what it is supposed to do). I am using VB.NET
View 4 Replies
Jun 29, 2010
When a user logs in into my website I have a custom membership provider that overrides ValidateUser and verifies that the user has sufficient rights etc.
However, when implementing a 'remember me' function through the default forms authentication using RememberMeSet, I also want to validate a user on the first request.
Is there some hook I can attach to that triggers when a user logs in with their persistent cookie?
View 3 Replies
Oct 31, 2010
Without reading the whole text below, since this is on the ASP.Net side ... basically I think I need to know if there is a way to reduce the size of the forms authentication cookie. When using a DotNet 2.0 website, the ASPXAUTH cookie is about 232 bytes ... when using the same source code but upgraded to DotNet 4.0. the cookie is approximately 264 bytes, setting the ticketCompatabilityMode does not reduce the size since I think the default setting is Framework20. I length of the cookie, including the its' name can not be larger than 256 bytes in order to use it with the "Client Application Services".
I only did a cursory search of the asp.net forums, but will dilligently look for an existing solution.
----- BACKGROUND AND RESEARCH -----
I have been using all three features of client application services (authentication, profiles, and roles) in my windows app (DotNet 3.5 framework) for almost two years now. Up until now, I have not had any problems. This week I hit a brick wall and am pretty stumped with two seperate but related issues.
Issues:
In development, we decided to upgrade our websites/services to DotNet 4.0. All applications upgraded successfully. However we are unable to log into our application using Client Application services. No matter what user we use, Membership.ValidateUser returns false. Since we know the username and passwords, we thought this was strange. When debugging the application, we found that Membership.ValidateUser was throwing an InvalidOperationException (see below for complete exception) stating that the ASPXAUTH property was too long, longer that the schema created in the SQL/CE database. (See below for things tried).
In production .. A user all of the sudden could no longer gain access to the application. Upon inspection, his ASPXAUTH cookie was 264 characters long (9 characters longer than the schemas nvarchar(256)). Even though the user was being authenticated on the "server side", and the JSON query returned "{"d":true}", Membership.ValidateUser returned false. Again, as in the case above, the actual error was ...
Message=@PropValue : String truncation: max=256, len=264 ...
I am assuming I am missing something very simple or that I overlooked a settings. In development, this is not a huge issue as I can release the Dotnet 4.0 websites when I am ready. But now that this has happened to a client on a production system, it is very worrisome.
[code]....
View 1 Replies
Jan 28, 2013
I use Form Based Authentication in my siteIn my login page I have:
FormsAuthentication.SetAuthCookie(user.userName, true)
View 1 Replies
Oct 13, 2010
I create custom principal for implement logic for users. In identity I store Id, Name. But it abnormally - this classes must use for authenticate and authorize.
I can implement custom MembershipUser, custom Roles and Membership provider.
How to do it? What best practices are?
View 5 Replies
Jan 31, 2010
I'd like to learn how to create custom providers ( say custom membership provider or custom profiles ) that use XML as their data store. Is ( using C# ) best way to accomplish this using XPath/XSLT or DOM?
View 1 Replies
Apr 18, 2010
so after a short talk with some people around ASP.NET MVC forum I took a huge step and chose to create my own Custom Membership Data provider.. so I logged into sweet google and started searching , it doesnt look that hard and seems totally possible for me , that's what i thought...
So now I opened visual studio , and started to think on few things .. So before I would start typing code , I would like to ask those questionsSo i would know better
1. when I build an SQL object , or XML or w.e object, how do I know which fields I need for my table ? should i just copy them from aspnetdb or is there somewhere it is written?
2. how the heck do I copy lines from webconfig ? and should I get those lines like "reset password" from web config or not?
3. I saw some parameters in "create User" called providerKey or something like that, and also MembershipState ? what exacly are those ?
4. last question: the functions get username , and password and stuff like that , but what If i want to create my own User Entity , is there a way to change what the function gets ? or should i just make another class that get my custom UserEntity and let the first class to send her the userentity as repository ?
View 1 Replies
Feb 10, 2011
I try to create a persistent cookie to store a preferred language on our website, but it doesn't work.
So, to isolate the problem, I created a new website, with a blank page and with the code behind bellow. If I click the button, the page post back and I get this:
"Cookies expires: 0001-01-01 00:00:00 value: 10"
[Code]....
View 5 Replies
Mar 21, 2010
I'm new to ASP.NET and I don't exactly understand some features.
I have a custom membership provider TestMembershipProvider which inherits from MembershipProvider. It has the following CreateUser method:
[Code]....
It's absolutely simple code.Then I have two text boxes (login, password) and the button to register a new user. I thas a following code:
[Code]....
[Code]....
Authentication in web.config is set like this:
[Code]....
No matter what I write into textboxes, following error is being returned:
The password retrieval question provided is invalid.
I don't know why. Either in web.config or in get RequiresQuestionAndAnswer I have false value. When I instantiate my TestMembershipProvider and call CreateUser directly instead of using static Membership.CreateUser, it works fine. Do I have to use instance of my TestMembershipProvider or did I missed anything?
View 1 Replies
Apr 16, 2010
I have created my custom MembershipProvider. I have used an instance of the class DBConnect within this provider to handle database functions. Please look at the code below:
public class SGIMembershipProvider : MembershipProvider
{
#region "[ Property Variables ]"
private int newPasswordLength = 8;
private string connectionString;
private string applicationName;
private bool enablePasswordReset;
private bool enablePasswordRetrieval;
private bool requiresQuestionAndAnswer;
private bool requiresUniqueEmail;
private int maxInvalidPasswordAttempts;
private int passwordAttemptWindow;
private MembershipPasswordFormat passwordFormat;
private int minRequiredNonAlphanumericCharacters;
private int minRequiredPasswordLength;
private string passwordStrengthRegularExpression;
private MachineKeySection machineKey;
**private DBConnect dbConn;**
#endregion
.......
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
if (!ValidateUser(username, oldPassword))
return false;
ValidatePasswordEventArgs args = new ValidatePasswordEventArgs(username, newPassword, true);
OnValidatingPassword(args);
if (args.Cancel)
{
if (args.FailureInformation != null)
{
throw args.FailureInformation;
}
else
{
throw new Exception("Change password canceled due to new password validation failure.");
}
}
SqlParameter[] p = new SqlParameter[3];
p[0] = new SqlParameter("@applicationName", applicationName);
p[1] = new SqlParameter("@username", username);
p[2] = new SqlParameter("@password", EncodePassword(newPassword));
bool retval = **dbConn.ExecuteSP("User_ChangePassword", p);**
return retval;
} //ChangePassword
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
......
ConnectionStringSettings ConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];
if ((ConnectionStringSettings == null) || (ConnectionStringSettings.ConnectionString.Trim() == String.Empty))
{
throw new ProviderException("Connection string cannot be blank.");
}
connectionString = ConnectionStringSettings.ConnectionString;
**dbConn = new DBConnect(connectionString);
dbConn.ConnectToDB();**
......
} //Initialize
......
} // SGIMembershipProvider
I have instantiated dbConn object within Initialize() event. My problem is that how could i dispose off this object when object of SGIMembershipProvider is disposed off. I know the GC will do this all for me, but I need to explicitly dispose off that object. Even I tried to override Finalize() but there is no such overridable method. I have also tried to create destructor for SGIMembershipProvider.
View 2 Replies
Feb 7, 2011
I was made a custom membership provider.
All works good. My problem is Logs.
[Code]....
[Code]....
I dont know how to get user's ip.
I tried these methods...
Dim req as httprequest
ip = req.servervariables("remote_host") 'result = nothing
Dim req as new httprequest
ip = req.servervariables("remote_host") 'result = nothing
Dim req as requestcontext
ip = req.request.servervariables("remote_host") 'result = nothing...
View 2 Replies
Jan 26, 2011
I recently got a form to work with the "HttpContext.Current.User.Identity.Name.ToString" String. That basic idea was I needed a hidden form field so that each record submitted would include the UserName of the user logged in to the membership. However, whenever I try to create a custom query for the gridview, it doesn't submit. how I would go about doing this? Code as below:
[Code]....
[Code]....
View 2 Replies
Jan 24, 2011
I need to use the standard ASP.NET membership database tables in plain winform projects, and I DO NOT WANT to add the ASP.NET dll, because my app must run with .NET Client framework, and not full framework. Does somebody knows of a helper class that links to ASP.NET tables in plain vanilla VB ot c# code? I mean with functions equivalent to CreateNewUser, CheckUserCredentials, isUserinRole, RoleList etc...
View 1 Replies
Jun 29, 2010
I have been diligently learning all about the asp.net membership framework and have a test site running it all. However, during my testing, it became apparent that deleting users would be useful. I can delete users from the "aspnet_users" & "aspnet_Membership" tables simply by right-clicking on the table in server explorer, selecting "show table data", highlight the rows and press delete!!
However, this is a pain and I would much rather do this properly from code behind.
I have found out that the membership schema supplies a large number of "stored procedures" including "Delete_Users" however, when I execute this one manually, I have no idea what the last two parameters are (number of tables and something else from memory - the first two "application name" and "username" are easy to copy in to the dialog.
show me a sample set of VB code that I can use behind a "Delete User" button on my webform including how I supply the parameters. I have set up a drop down list box from teh "aspnet_users" table which displays the "UserName" and has as the SelectedValue "UserId".
View 3 Replies
Jul 25, 2010
we use forms authentication for a community website with about 200k users with a simple login like this:
Private Sub btnLogIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogIn.Click
If CheckPassword(txtEmail.Text, txtPassword.Text)
FormsAuthentication.RedirectFromLoginPage(txtEmail.Text, chkRememberMe.Checked)
End If
End Sub
which checkPassword reads from a MS SQL users table. it has worked without major problems for 3 years but we need to store the login date of users in a table, both when they login explicitly and when they had selected "remember me" and come back (we store login once per session)
since we have a complicated profile system and database it will be practically impossible to switch to membership API. last time I was told we could user an auditing system to do that but I have no idea how to do that.
View 2 Replies