473,725 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Membership Provider Woes

I have been having some trouble with implementing a custom Membership
Provider. We have a custom data store and business logic that pulls user
information. I need some level of functionality above and beyond what the
prodiver currently allows. I need the ability to access a user id and the
user's permission id. With Forms authentication in 1.1, I would just create
a custom identiy and principal and store the information in the identity.
However, the membership provider doesn't quite support this. I can get the
login conrols to work properly with my custom membership provider, I just
can't find a way to expose more information about a user from my custom
classes. I've looked at the profile provider; I haven't had success with
that either. That doesn't seem to want to store information in an
authentication ticket like the membership provider does. Ideally I would
like everything stored in the authentication ticket (as it is with the
membership provider). I don't want to have to go to the database everytime
the page loads just to get the user id.

Sooooo...my basic requirements are as follows.
1. Use asp.net Login Controls
2. On any page, at any time, I want to know the current logged in user's id
3. On any page, at any time, I want to know the current user's permission id

So, I just want to retrieve two integer values on top of what the membership
provider gets me. I would like to avoid implementing the profile and role
provider because i feel it would be overkill. Also, I don't want to do
authentication via the session, or manually via cookies. I would like to
leverage the provider model, but I can't get it to do exactly what I need.

Can anyone help me expose this additional information without going to the
database everytime? Thanks
Dec 22 '06 #1
4 4732
Hello Chris,

From your description, you are using the Membership/Role providers to
perform forms authentication in your ASP.NET web application. You like the
built-in membership/role provider feature and the login controls, however,
you also want to add additional custom data(specifci to each user) into the
forms authentication cookie (without querying database in each request),
correct?

Based on my experience, since ASP.NET 2.0's membershp/role provider and
service model has been well encapsulated, it is not quite convenient to
modify it or develop our own model to replace them. And what you need here
is just cache some custom data into forms auth ticket and used in other
pages later, I think you can simply add them into the
FormsAuthentica tionTicket(crea ted manually) and then access it later
through the FormsIdentity.T icket property. e.g.

========in page which want to access the custom data in authenticatino
ticket=======
protected void Page_Load(objec t sender, EventArgs e)
{

//you can even define a helper function for extract custom data from
ticket.UserData string
Response.Write( "<br/>CurrentIdentit y: " + Context.User.Id entity);

FormsIdentity identity = Context.User.Id entity as FormsIdentity;

Response.Write( "<br/>Ticket.UserDat a: " + identity.Ticket .UserData);
}
===============

the forms authentication module will help retrieve teh userdata from
ticket(from cookie) and store it in the FormsIdentity(i n the
HttpContext.Cur rent.User.Ident ity). Also, in your login page, you need to
manually create the FormsAuthentica tion ticket so that you can add
additional data into "UserData" property of the ticket. e.g.

=========in our custom logging page's code=========== =
protected void Login1_LoggingI n(object sender, LoginCancelEven tArgs e)
{
FormsAuthentica tionTicket ticket = new FormsAuthentica tionTicket(
1,
Login1.UserName ,
DateTime.Now,
DateTime.Now.Ad dMinutes(30),
Login1.Remember MeSet,

"some custom data want to store in ticket....", // User-data, in
this case the roles
FormsAuthentica tion.FormsCooki ePath);
string hash = FormsAuthentica tion.Encrypt(ti cket);
HttpCookie cookie = new HttpCookie(
FormsAuthentica tion.FormsCooki eName,
hash);
if (ticket.IsPersi stent) cookie.Expires = ticket.Expirati on;
Response.Cookie s.Add(cookie);

Response.Redire ct(Request.Quer yString["ReturnUrl"]);

}
=============== =============

Hope this helps for your scenario.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

=============== =============== =============== =====

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.

=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Dec 25 '06 #2
Thanks Steven,

I have a few questions. The FormsIdentity class you reference, is that a
custom class I have to write that implements IIdentity or is it just
available.

Second, how do I actually store the custom information? From the looks of
it, I pass infomration into the constructor of the FormsAuthentica tionTicket,
but which parameter does it? Is it the "1" that you pass in?

How can I easily access this information later? It looks like once you pass
the information into the cookie, you can pull it out using
identity.Ticket .UserData. However, isn't this just implementing a custom
IIdentity...whi ch is kind of the asp.net 1.1 way?

Doens't the membership provider set a forms auth cookie for me
automatically? Will setting the cookie manually cause a problem?

Is there any way to intercept the data from the Membership provider? As it
stands, the membership provider will go to the database to authenticate the
user, then I will have to go to the database manually again just to get their
user information. I tried finding an event that would return the data as
with an objectdatasoure , but I haven't found any. Is there any way to avoid
this extra call that the Membership provider is doing anyway.

It's a little disappointing that I have to do so much hacking to get
something so simple to work. I would have thought .net 2.0 would have
covered this a little better.

"Steven Cheng[MSFT]" wrote:
Hello Chris,

From your description, you are using the Membership/Role providers to
perform forms authentication in your ASP.NET web application. You like the
built-in membership/role provider feature and the login controls, however,
you also want to add additional custom data(specifci to each user) into the
forms authentication cookie (without querying database in each request),
correct?

Based on my experience, since ASP.NET 2.0's membershp/role provider and
service model has been well encapsulated, it is not quite convenient to
modify it or develop our own model to replace them. And what you need here
is just cache some custom data into forms auth ticket and used in other
pages later, I think you can simply add them into the
FormsAuthentica tionTicket(crea ted manually) and then access it later
through the FormsIdentity.T icket property. e.g.

========in page which want to access the custom data in authenticatino
ticket=======
protected void Page_Load(objec t sender, EventArgs e)
{

//you can even define a helper function for extract custom data from
ticket.UserData string
Response.Write( "<br/>CurrentIdentit y: " + Context.User.Id entity);

FormsIdentity identity = Context.User.Id entity as FormsIdentity;

Response.Write( "<br/>Ticket.UserDat a: " + identity.Ticket .UserData);
}
===============

the forms authentication module will help retrieve teh userdata from
ticket(from cookie) and store it in the FormsIdentity(i n the
HttpContext.Cur rent.User.Ident ity). Also, in your login page, you need to
manually create the FormsAuthentica tion ticket so that you can add
additional data into "UserData" property of the ticket. e.g.

=========in our custom logging page's code=========== =
protected void Login1_LoggingI n(object sender, LoginCancelEven tArgs e)
{
FormsAuthentica tionTicket ticket = new FormsAuthentica tionTicket(
1,
Login1.UserName ,
DateTime.Now,
DateTime.Now.Ad dMinutes(30),
Login1.Remember MeSet,

"some custom data want to store in ticket....", // User-data, in
this case the roles
FormsAuthentica tion.FormsCooki ePath);
string hash = FormsAuthentica tion.Encrypt(ti cket);
HttpCookie cookie = new HttpCookie(
FormsAuthentica tion.FormsCooki eName,
hash);
if (ticket.IsPersi stent) cookie.Expires = ticket.Expirati on;
Response.Cookie s.Add(cookie);

Response.Redire ct(Request.Quer yString["ReturnUrl"]);

}
=============== =============

Hope this helps for your scenario.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead

=============== =============== =============== =====

Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.

=============== =============== =============== =====

This posting is provided "AS IS" with no warranties, and confers no rights.

Dec 26 '06 #3
Thanks for your reply Chris,

Regarding on your new questions ,here are my understanding on this:
The FormsIdentity class you reference, is that a
custom class I have to write that implements IIdentity or is it just
available.
=============== =============== ========
Sure, it is a built-in class which is used to represent security identity
in forms authentication context. This is used in both ASP.NET 1.x and 2.0
by the forms authentication Module, it will be automatically created in
each request(as long as the current user has been authenticated).
Second, how do I actually store the custom information? From the looks of
it, I pass infomration into the constructor of the
FormsAuthentica tionTicket,
but which parameter does it? Is it the "1" that you pass in?
=============== =============== ===========
No. "1" is the version number. It is the "some custom data want to store in
ticket...." which can be any custom data you want to store in the
authentication ticket. Custom data can only be string value, it is also
limited by the natural of cookie. You find the clear definition of the
Ticket class's constructor below:

#FormsAuthentic ationTicket.For msAuthenticatio nTicket(Int32, String,
DateTime, DateTime, Boolean, String, String) Constructor
http://msdn2.microsoft.com/en-us/library/kybcs83h.aspx

How can I easily access this information later? It looks like once you
pass
the information into the cookie, you can pull it out using
identity.Ticket .UserData. However, isn't this just implementing a custom
IIdentity...whi ch is kind of the asp.net 1.1 way?
=============== =============== =============
As I have mentioned, FormsIdentity is a built-in class dedicated for
representing forms authenticated user identity, this is used from 1.x to
2.0. You can easily get this identity in each page request through
HttpContext.Cur rent.User. Also, ASP.NET 2.0 is using the same means to
create forms authentication ticket and store it in cookie, and retrieve it
back in each request(in FormsAuthentica tion httpmodule). There is no
difference on these code, the only difference is that ASP.NET 2.0 have done
this for you internally and save you from coding these yourself. So what
you need to do is just add the custom string data at user's
login/authentication time and then access it through Context.Use whenever
you need it.
Doens't the membership provider set a forms auth cookie for me
automatically? Will setting the cookie manually cause a problem?
=============== =============== ==============
Well, this is a good question. ASP.NET 2.0 add the membership service which
can help simplify the custom security/user management. However, remember
that membership provider and forms authentication are totally separated,
you can use forms authentication without membership service(do it yourself
as ASP.NET 1.X). Or you can simply call membershp API without enabling
forms authentication.

No, "setting cookie manually" won't cause any problem, ASP.NET 2.0
FormsAuthentica tions class use the same code to generate the ticket and add
it into resposne cookie collection(defa ult behavior). Here is the
diassembled code from reflector
>>>>>>>FormsAut hentication.Get AuthCookie>>>>> >>>>>>>>
private static HttpCookie GetAuthCookie(s tring userName, bool
createPersisten tCookie, string strCookiePath, bool hexEncodedTicke t)
{
FormsAuthentica tion.Initialize ();
if (userName == null)
{
userName = string.Empty;
}
if ((strCookiePath == null) || (strCookiePath. Length < 1))
{
strCookiePath = FormsAuthentica tion.FormsCooki ePath;
}
FormsAuthentica tionTicket ticket1 = new FormsAuthentica tionTicket(2,
userName, DateTime.Now, DateTime.Now.Ad dMinutes((doubl e)
FormsAuthentica tion._Timeout), createPersisten tCookie, string.Empty,
strCookiePath);
string text1 = FormsAuthentica tion.Encrypt(ti cket1, hexEncodedTicke t);
if ((text1 == null) || (text1.Length < 1))
{
throw new
HttpException(S R.GetString("Un able_to_encrypt _cookie_ticket" ));
}
HttpCookie cookie1 = new
HttpCookie(Form sAuthentication .FormsCookieNam e, text1);
cookie1.HttpOnl y = true;
cookie1.Path = strCookiePath;
cookie1.Secure = FormsAuthentica tion._RequireSS L;
if (FormsAuthentic ation._CookieDo main != null)
{
cookie1.Domain = FormsAuthentica tion._CookieDom ain;
}
if (ticket1.IsPers istent)
{
cookie1.Expires = ticket1.Expirat ion;
}
return cookie1;
}
<<<<<<<<<<<<<<< <<<<<<<<<<<<<<< <

Since you need to add custom data here, you need to manually create the
Ticket and add it into response's Cookie collection. All the API used here
are public ones, nothing incorrect.
Is there any way to intercept the data from the Membership provider? As it
stands, the membership provider will go to the database to authenticate the
user, then I will have to go to the database manually again just to get
their
user information. I tried finding an event that would return the data as
with an objectdatasoure , but I haven't found any. Is there any way to
avoid
this extra call that the Membership provider is doing anyway.
=============== =============== =============== ===
Membership API has nothing to do with forms authentication. Membershp API
just help retrieve or update the data in membership database tables. If
you're using forms authentication and want to store cached data through
forms authentication ticket, you should use forms authentication API rather
than membershp API.

If there is anything unclear, please feel free to let me know.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.

Dec 27 '06 #4
Hi Chris,

Thanks for your followup.

Due to caught a bad cold, I haven't had a chance to visit the newsgroup the
previous days.

For the questiosn you mentioned in the last reply:

You set the FormsAuth ticket on the Login_LoggingIn . Is
there any reason you did that instead of Login_LoggedIn? You're setting a
cookie regardless of whether the user's authentication failed or not.
=============== =============== =============

I think put the code in LoggingIn event rather than LoggedIn event is
important. This is because the Login control will automatically do the user
validation(thro ugh membership API) and generate the default authentication
ticket and add into cookie collection after the LoggingIn event before
LoggedIn event. Since we want to generate and set the authentication
ticket/cookie ourself, we should hook the code in "LoggingIn" event.

Also, I admit that the code snippet in my previous message is a bit
incomplete, the complete code logic in the LoggingIn event should look like
below:
>>>>>>>>>>>>>>> >>>>>>>>>>>>>>> >
protected void Login1_LoggingI n(object sender, LoginCancelEven tArgs e)
{
//cancel it to avoid further default codelogic of login control

e.Cancel = true;

//manually use membershp API to do the authentication
if (Membership.Val idateUser(Login 1.UserName, Login1.Password ))
{
FormsAuthentica tionTicket ticket = new
FormsAuthentica tionTicket(
1,
Login1.UserName ,
DateTime.Now,
DateTime.Now.Ad dMinutes(30),
Login1.Remember MeSet,

"some custom data want to store in ticket....", // User-data,
in this case the roles
FormsAuthentica tion.FormsCooki ePath);
string hash = FormsAuthentica tion.Encrypt(ti cket);
HttpCookie cookie = new HttpCookie(
FormsAuthentica tion.FormsCooki eName,
hash);
if (ticket.IsPersi stent) cookie.Expires = ticket.Expirati on;
Response.Cookie s.Add(cookie);

Response.Redire ct(Request.Quer yString["ReturnUrl"]);

}
}
<<<<<<<<<<<<<<< <<<<<<<<<<<<< <<

In addition, you're welcome to post any request or feedback about the
enhancement on such feature in our product feedback center:

http://connect.microsoft.com/VisualStudio/feedback/

Thanks again for your posting.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead
This posting is provided "AS IS" with no warranties, and confers no rights.

Dec 29 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2445
by: Morgan | last post by:
Sorry for cross post, forgot to include aspnet in orinal... Thanks in advance for any assistance. I'm in the process of implementing custom RoleProvider & Membership Provider objects and have run into a snag with the Membership Provider. It seems many of the MembershipUser properties are read-only. This seems, well stupid, IMO.
2
3559
by: John | last post by:
Hi I was working fine with create user wizard and the default membership provider. I have now customised the membership provider as per attached web.config. The create user wizard picks up the custom membership provider fine and removes the security question/answer fields as designated in the custom provider. The problem is that when I try to create a new user in the create user wizard by entering the info and pressing the 'create...
3
7132
by: ad | last post by:
I have create a custom membership provider. The common usage of custom membership is set it as default Membership Provider win web.config, and use login controls with it. How can I use custom membership provider without Login Controls? For example, the name of my custom membership provider MyMembershipProvider. Is the codes below right? MyMembershipProvider myProvider=new MyMembershipProvider();
9
2174
by: Paul Keegstra | last post by:
Hi, I am currently working on an asp.net 2.0 web site that is a replacement of a classic asp web site. The current web site uses a Commerce Server 2002 database for storing user information. It does not currently use any of the Commerce Server 2002 functionality with the exception of the user authentication features. I have written my replacement application to use a custom login form and custom connection string so that I can use...
2
14156
by: Balaji | last post by:
Hi All, Can I use more than one membership provider for a given website? I understand only one of them could be default one. If yes, then how to programmatically access the other membership provider? For e.g. lets say I have a SQLMembership provider and OracleMembership provider. SQL would be my default provider. During authentication, based on the value of an additional parameter in the login screen, I need to validate against SQL or...
3
3280
by: ryan.mclean | last post by:
Hello everyone, I am wondering, can the membership provider be changed at runtime? Perhaps the connectionStringName? I would like to use a different database based on the server the site is on. I suppose that a custom provider could be used to accomplish this, is there another way?
4
7233
by: thomas | last post by:
Hello All, How to change the default Membership Provider during the runtime? I know I can reference any provider I want, e.g.: provider = Membership.Providers but the question is how to change the default one, so all those new, cool controls can start using the one I want. I can specify the provider for each of those controls, e.g.:
1
14316
by: Ben | last post by:
Hi, When an anonymous user has created an new account (with the CreateUserWizard control), i want to let asp.net generate a password and to send it to the address of the email provided by the new membershipuser in the CreateUserWizard control. i think i need to define a custom provider for membership and i tried this: web.config:
6
2931
by: Jonathan Wood | last post by:
Although this will be a challenge at my level of ASP.NET knowledge, I'm thinking I should implement my own membership provider class. Looking over the methods I must implement, a number of questions come to mind. 1. How would one implement GetNumberOfUsersOnline? I'm not sure where there is any indication of this? And it this affected by the "Remember me next time" checkbox, which doesn't seem to work like it does on any other site...
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9174
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9111
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8096
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4517
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.