Membership and Roles

Monday, November 28, 2005

I like to write about a topic before I give a presentation. Writing is my way of organizing random thoughts into an arbitrary collection of opinions.

When I signed up to do a presentation at the last local code camp, I got behind on writing about membership and role providers in ASP.NET 2.0. I finally finished the writing this weekend (Part I, Part II).

Miguel Castro also covered membership features at the last code camp. Miguel concentrated on the login controls and UI customization while I stuck more to the configuration and other details. Miguel knows a great deal about ASP.NET server controls –just listen to his .NET Rocks appearance. Two thumbs up!


Comments
Steinar Wednesday, November 30, 2005
Great article... but I'm looking for information about Membership providers for Active Directory. Have you looked into it? Or do you have any good links??

Thanx...
vish Monday, January 16, 2006
Excellent article.

But I m looking for an article which shows that how to create your own custome membership provider.... And there's a lot of links and material available on this topic...

But none of them shows how to use your existing database.... rather than using the .Net's default database.

If I have my existing database in the access or sql server... n it has user table with the field username, password n their roles then how to use it to gain the features of this membership provider class....

If u require n e further info... then let me know...

N if u know n e other relevant materials or links or urself having knowledge of it... then pl let me know about that too.

my email id - vishal_027@yahoo.co.in

thnx.....



Yevgeniy Wednesday, January 18, 2006
I am also interested in the issue touched upon in the previous post. So what is your suggestion on this account?
Scott Allen Thursday, January 19, 2006
The provider whitepapers are about the best reference for those who want to build thier own (other than Reflector, that is):

msdn.microsoft.com/.../default.asp
dominick Tuesday, January 24, 2006
It is better to use Context.User.IsInRole than Roles.IsUserInRole, because:

a) the usage of RoleManager is an implementation detail. Context.User is a more general concept.

b) Roles.IsUserInRole calls RolePrincipal.IsInRole under the hood, anyway.

good article!
Scott Tuesday, January 24, 2006
Thanks for the tip, Dominic.
Mike Wednesday, January 25, 2006
There's more information about profile providers here:

SqlTableProfileProvider

and this is the download link:
Info at ASP.NET

Good info in the refered samples..

Mike
_________________
nz website design
Mike Wednesday, January 25, 2006
Sorry about the above post - wasn't sure how links were done in the blog.. 2nd attempt:

There's more information about membership profile providers here:

weblogs.asp.net/.../435038.aspx

and this is a good download link for a SQL table provider:
www.asp.net/.../samp_profiles.aspx

Good info in the refered samples..

Mike
______________________
http://www.ediy.co.nz
Nir Thursday, January 26, 2006
Hi,
Great artical.

You mention that the configuration of the provider is on the machine.config. which mean all site on that machine must use the same provider.
What about multiple provider on the same machine?
For example, I wrote a custom provider for my site but other site on the same machine use the default provider.

10X
Niro
scott Thursday, January 26, 2006
Niro: The machine.config settings provide a default for the entire machine. You can override the default with a web.config setting.
sp_412000@yahoo.com Sunday, February 5, 2006
These are the excellent articles. I read lot of articles, but all explained about just controls not behind the scene functionality. Excellent work. Just excellent.
Scott Tuesday, February 14, 2006
Uh, this doesn't work. I get an error when I add the connectionStrings element to my web.config.

scott Tuesday, February 14, 2006
Scott: That generally means the site is not configured for 2.0, but is using the 1.1 web.config schema.

If that's not the case then email or post the specific error message and I can try to help.
Scott Tuesday, February 14, 2006
uhh, never mind. I put it in the wrong place and didn't notice that it was already defined in the web.config. (insert the sound of a hand slapping a forehead here)
Matteo Wednesday, February 15, 2006
I would like to know if it's possible the customization of user or userProvider class.
I would like to add some properties, like the display name to use instead of username for the welcomeLabel, or others properties like employeeID.
I not finding the right way... can anyone help me?
scott Wednesday, February 15, 2006
Hi Matteo:

Have you looked at the Profile features? http://www.odetocode.com/Articles/440.aspx
kukabuka Thursday, March 2, 2006
How to export/import membership data?

Here's the scenario:
Using SQL Express after running the aspnet_regsql wizard for both the SqlMembershipProvider and SqlRoleProvider.

I've entered some users and roles, and everything looks good on my development machine. Now I want to export that stuff to a live server that I have also run the aspnet_regsql wizard on.

The data does not copy nicely with SQL Server Management Studio because of foreign key errors. There seems to be no way to easily copy the data without disabling foreign keys.

Surely there is a solution for this common scenario?

Thanks.
scott Sunday, March 5, 2006
kukabuka: You'll have to make sure to copy the tables in the right order to keep foreign keys in tact.
Yu Tuesday, March 14, 2006
Excellent article! The for your info.
I'm starting to write some ASP .Net 2.0 applications and your articles are very useful.
But is it possible to do 'single sign on'? Is it possible to customized the login controls? (e.g. when a specific user account tried several times. an alert will send to admin?)

More, must I use access, sql or AD? Any provider for LDAP?
Thx for your attention.

scott Tuesday, March 14, 2006
Yu:

You can certainly customize the login control to send an alert. As for access, it's tough to say without more requirements.
There is some info on MSDN:
msdn.microsoft.com/.../singlesignon.asp?frame=true
Yu Wednesday, March 15, 2006
Hi Scott,
thx for the article. I'm studying it now. However, so, there're no LDAP membership provider for asp.net 2.0 yet?
scott Wednesday, March 15, 2006
The closest thing is the ActiveDirectoryMembershipProvider, which talks LDAP to Acive Directory (I'm assuming).
Nico Tuesday, April 18, 2006
Hi Scott,

it`s a very good article. Please could you explain me, how to use the MembershipUser-Object that is returned by the CreateUser method. I dont understand the functionality of this object. Do i need this object for DB-Access or rolemanagement?

thx for answering

Nico
scott Tuesday, April 18, 2006
The MembershipUser object represents the new user in the database. You can use it to update what is in the database for that user.
lance Saturday, April 29, 2006
I want to have a web application ultilize Membership and roles that works for different companies. Each company will have its own database and identical db structure for aspnet membership and roles.
You would expect to see the login control with username, password, and companykey. A connectionstring will be derived from the companykey.
How do I put this connection string to work with the .Net built in Membership components. The only way I know is to preset this connectionstring in web.config and associate it with the provider.
I appreciate with any pointers.
Lance
scott Tuesday, May 2, 2006
Lance:

The connection strings for 2.0 (even for the providers) have moved into the connectionStrings section of the web.config file.
Bill Tuesday, May 9, 2006
Why are there never any details offered on asp.net 2.0 membership about allowing for an admin page in which the admin can reset passwords without knowing the old password.

A programatic way to change passwords has to be possible without storing user passwords in another way, simply to have them available to change the password.

Impu Tuesday, May 9, 2006
Very nice article (I have learned a lot from it). I would highly anticipate that you write a forms based authentication that utilizes Active Directory. Pretty much everyone who has Windows Network and working with ASP.NET 2.0 apps, they are thinking in and around Active Directory, Federation Services, single sign-on blah blah. Please continue your great work and focus on that area. I have seen some out there, but pretty much all are "Windows Auth" or Forms, nothing about "both" (I have heard some performance issue with AzMan).
aferende Friday, May 12, 2006
Hi,

I’m writing you to suggest a product similar to MS Authorization Manager, that I have written and published as open source at: .NET Sql Authorization Manager (NetSqlAzMan). http://netsqlazman.sourceforge.net

Here a short description of NetSqlAzMan:
The .NET Sql Authorization Manager allows you to set "Item-based" permissions for Authorization Manager-enabled Microsoft .NET 2.0 applications (Smart client & Web apps). Storage reside on a DataBase MS Sql Server (2000/MSDE/2005/Express).

Andrea.
Steve Tuesday, May 16, 2006
Excellent article. We are looking at adopting this approach in our recently 1.1->2.0 migrated codebase where we have an existing user and role management module. What I'm trying to find out is whether the ASP 2.0 RoleProvider can be extended so that I can define different sets of roles in the one database. That is, I need a set of Users (Tom, Dick and Harry) to be attributable to Roles (A, B and C) but another set of Users (Danny, Justin, Adam and Maynard) to be attributable to Roles (X, Y and Z). I dont want Users from one organization being able to have Roles in the other organization (Maynard can only have Role X but never A). Does the underlying model support this separation of Roles based on some other business property? Can I easily extend the Role in this way or will I need to write a fair chunk of extra code to support this differentiation? Any feedback welcome. Thanks in advance.
Hugo Tuesday, May 23, 2006
Hi. I'm having problems with an authorization store role provider that I'm using in my web site. The problem is the updating of the roles cookie. For exmaple, If a query the existing roles in the AzMan store I get the full list in the XML file (OK to the moment), but if I create a rol programatically or add a user to a role or whatever related to writing or modifiyng the file, I don`t get the changes at the moment, not even if I close the page and restart it again!. Actually, if I modifiy the AzMan store through the AzMan console and I run the web site proyect, I get the previous values before the changes. In fact, the only way I've found for the list of roles to be updated is by modifying the web.config file (for example, by inserting a white space anywhere in the file) and run the proyect again.
This is the configuration I have:

<roleManager enabled="true"
cacheRolesInCookie="false"
defaultProvider="RoleManagerAzManProvider"
cookieName=".ASPXROLES"
cookiePath="/"
cookieTimeout="1"
cookieRequireSSL="false"
cookieSlidingExpiration="false"
createPersistentCookie="false"
cookieProtection="All">
<providers >
<add connectionStringName="LocalPolicyStore" applicationName="Logica" name="RoleManagerAzManProvider" type="System.Web.Security.AuthorizationStoreRoleProvider, System.Web, Version=2.0.0.0, &#xA; &#xA; Culture=neutral, publicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>

If you could help me I would appreiate it a lot. Thanks for your time
Dave Friday, June 2, 2006
This is a great article. I do have one question. I set up the membership provider and role provider and have the site running great in a development environment. I can copy it out to a production server and everything runs great. My question is how do we manage the users from there? I don't see a way to pull up the asp.net web site administration tool on the production server. Any help would be greatly appreciated.
Joannes Vermorel Sunday, June 4, 2006
I would like to know how I can emulate the Membership.CreateUser method with the aspnet_Membership_CreateUser stored procedure.
Can somebody give me a directly, up to know I am stuck with the Password, PasswordSalt arguments plus the hashing behavior.

Can someone tell me how I can achieve that? Thanks in advance, Joannès
Doom Sunday, June 11, 2006
Basically i am working on the Default login features provided.... i need to retrieve the username from the membership database after logged in is done, store somewhere and allowed me to retrieve it to store as foregin key for other table...
Will Wednesday, June 21, 2006
I've got my app authenticating against AD but when I try to see if a user is in a certain group, "testgroup" in my case, using Roles.IsUserInRole("testgroup") gives me the following error:

"Method is only supported if the user name parameter matches the user name in the current Windows Identity."

I'm using Web Dev Express, maybe that's the problem?
scott Thursday, June 22, 2006
Will: I can't say I've seen that error. I doubt the problem would be a web dev express problem, though. I'd try asking in the forums at forums.asp.net.
Harry Thursday, July 27, 2006
Hi, Scott.

Any chance you have code on implementing a custom role provider using AzMan roles with ADAM with Forms web based authentication? I referened the MSDN version for odbc, but the implementation seems very differnt than using roles with Azman/ADAM.

Thanks in advance,
Harry
scott Friday, July 28, 2006
Harry:

I haven't worked with membership and Azman/ADAM as yet, sorry. It is something I have to do at some point in the future.
Shafiq Thursday, September 21, 2006
Nice article. One thing missing in this article is after your creating aspnetdb in your own server(non SQL Express). You have to grant authority to NT Authority\Network Service account to some of the schemas.
dcgate Tuesday, September 26, 2006
this is easily one of the most helpful articles on this issue i have found - great work. one problem i'm still having though:

i've added an existing remote database in my machine.config file, and i've set it as the membership/role provider in the configuration tool. everything seems to work fine on the development server, but not on my live hosting server. any ideas why this might be so? i'm wondering if it's something to do with the 'type' attribute of the provider elements?
scott Sunday, October 1, 2006
@dcgate: Any error messages or exceptions?
dupls Monday, November 13, 2006
I have battled with getting login/membership to work on a remote machine, localhost with ASPNETDB.MDF works just fine.
Finally I discovered this url and with it some great tips
I ran the wizard and entered the SQL server authentication username and password on the database.
I included the string of code for the config file relating to my new database
But if I test the provider in the asp.net tool I get this error.
Could not establish a connection to the database.
If you have not yet created the SQL Server database, exit the Web Site Administration tool, use the aspnet_regsql command-line utility to create and configure the database, and then return to this tool to set the provider.
I see that there is no additional user id or password repeated in the connectionstring but I'm guessing it doesn't need it. Although I have tried including it but I still get the same error.
What have I missed?
gravatar Tristan Friday, October 23, 2009
Hey i need some help, if this page is still even active.

managed to impliment fine, by i get a cast error when using memebership.getuser()

thanks
gravatar raj solanki Thursday, January 14, 2010
hi...
i am using sql server data base in my app not sql express database .but when i run the app then aspnet.db data base automatically come .

so plzz tell me what can i do for it..
gravatar scott Thursday, January 14, 2010
Try using aspnet_regsql: http://msdn.microsoft.com/en-us/library/ms229862(VS.80).aspx

Hope that helps!
SSB Wednesday, May 12, 2010
A question:
Can I use Asp.net Configuration tool for adding Roles and Users if I am using custome providers with a DB other than SQL Server say Ingres?
gravatar Miru Sharma Thursday, May 27, 2010
My Condition:
1. I have Sql Server installed and wants to operate with the database in Sql Server.
2. I tried to make custom membership provider and role provider by implementing sealed MembershipProvider and RoleProvider.

3.I have gone through the steps that you have mentioned in ur article.But I m geting the following error while I try to use security in ASP.Net Configuration.

"The method or operation is not implemented."

Please help me!!
You can email me @: p_meeru444@hotmail.com
Thank You!
gravatar Divyesh Sharma Friday, July 23, 2010
Can you pleas explain, how roles can be added dynamically?
gravatar Atiq Tuesday, November 2, 2010
What are <deny users="?"/> and <allow users="*"/> in <authorization> in ASP.net...
gravatar shrikant Monday, January 24, 2011
Hi,
I have a web page through this page when I try to add a new user then users created successfully but when try resetting their password then I am getting errors’

add New user successfully

public static void AddUser(ADUser adUser)
{
// Local variables
DirectoryEntry oDE = null;
DirectoryEntry oDENewUser = null;
DirectoryEntries oDEs = null;

try
{
oDE = GetDirectoryEntry(GetADPath(PROD, adUser.UserType));

// 1. Create user account
oDEs = oDE.Children;
oDENewUser = oDEs.Add("CN=" + adUser.UserName, "user");

// 2. Set properties
SetProperty(oDENewUser, "givenName", adUser.FirstName);
SetProperty(oDENewUser, "sn", adUser.LastName);
SetProperty(oDENewUser, "mail", adUser.Email);
SetProperty(oDENewUser, "sAMAccountName", adUser.UserName);
oDENewUser.CommitChanges();

/// 4. Enable account
EnableAccount(oDENewUser);

// 3. Set password
//SetPassword(oDENewUser, adUser.Password);
SetPassword1(oDENewUser.Path, adUser.Password);
oDENewUser.CommitChanges();

oDENewUser.Close();
oDE.Close();
}
catch (Exception ex)
{
throw ex;
}
}
I have try the following 2 SetPassword methods but getting error.
Method 1.
internal static void SetPassword1(string path, string userPassword)
{
//Local variables
DirectoryEntry usr = null;

try
{
usr = new DirectoryEntry();
usr.Path = path;
usr.AuthenticationType = AuthenticationTypes.Secure;
object ret = usr.Invoke("SetPassword", userPassword);
usr.CommitChanges();
usr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
The exception raised (Error Code 80072035: The server is unwilling to process the request)
Method 2.
internal static void SetPassword(DirectoryEntry de, string userPassword)
{
//Local variables
//DirectoryEntry usr = null;
string quotePwd;
byte[] pwdBin;

try
{
quotePwd = String.Format(@"""{0}""", userPassword);
pwdBin = System.Text.Encoding.Unicode.GetBytes(quotePwd);
de.Properties["unicodePwd"].Value = pwdBin;
de.CommitChanges();
//usr.Close();
}
catch (Exception ex)
{
throw ex;
}
}
The exception raised ("Exception has been thrown by the target of an invocation.")
Is there an easy way to tell if there is a problem with changing a password?
Please reply me as soon as possible.
Thanks.
gravatar scott Monday, January 24, 2011
Most problems with AD are security related. Does the web app run in a pool with an account that has permission?
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!