custom sql role provider problem

what i'm trying todo:

 Using windows authentication for the membershiop provider and a custom sql role provider for the roles.

 what is working:

- the memberschip provider is working perfectly oput of the box

- the role provider works when i'm using coding to check for certain rols: Roles.IsUserInRole(login, "AppEdit")

 Whats not working:

- everything to allow/deny roles in the web.conf file (<allow roles="foo" />)

my web.conf


2    <!-- 
3        Note: As an alternative to hand editing this file you can use the 
4        web admin tool to configure settings for your application. Use
5        the Website->Asp.Net Configuration option in Visual Studio.
6        A full list of settings and comments can be found in 
7        machine.config.comments usually located in 
8        \Windows\Microsoft.Net\Framework\v2.x\Config 
9    -->
10   <configuration>
11   	<appSettings/>
12   	<connectionStrings>
13       <remove name="LocalSqlServer"/> 
14   		<add name="MIIS_AuthorizationConnectionString" connectionString="*****" providerName="System.Data.SqlClient"/>
15   	</connectionStrings>
16   	<system.web>
17   		<!-- 
18               Set compilation debug="true" to insert debugging 
19               symbols into the compiled page. Because this 
20               affects performance, set this value to true only 
21               during development.
23               Visual Basic options:
24               Set strict="true" to disallow all data type conversions 
25               where data loss can occur. 
26               Set explicit="true" to force declaration of all variables.
27           -->
28   		<compilation debug="true" strict="true" explicit="true">
29   			<assemblies></assemblies>
30       </compilation>
31   ....
32       <authentication mode="Windows" />
33       <identity impersonate="false" />
34       <authorization>
35         <deny users="?"/>
36       </authorization>
37       <customErrors mode="Off">
38       </customErrors>
39       <roleManager enabled="true" defaultProvider="CustomRoleProvider">
40          <providers>
41            <clear /> 
42            <add name="CustomRoleProvider" connectionStringName="MIIS_AuthorizationConnectionString" type="CustomProviders.CustomRoleProvider" />
43          </providers>
44       </roleManager>
45     </system.web>
46   	<system.codedom>
47   	</system.codedom>
48   	<system.webServer>
49   	</system.webServer>
50   <location path="App.aspx">
51       <system.web>
52         <authorization>
53           <allow roles="meceukldi"/>
54           <deny users="*" />
55         </authorization>
56       </system.web>
57     </location>
58   </configuration>

my customclass:


1    using System;
2    using System.Data;
3    using System.Data.SqlClient;
4    using System.Configuration;
5    using System.Web;
6    using System.Web.Security;
7    using System.Web.UI;
8    using System.Web.UI.HtmlControls;
9    using System.Web.UI.WebControls;
10   using System.Web.UI.WebControls.WebParts;
11   using System.Collections;
12   using System.Collections.Generic;
13   using System.Collections.Specialized;
14   using System.Configuration.Provider;
15   using System.Xml;
17   namespace CustomProviders
18   {
19       public class CustomRoleProvider : RoleProvider
20   	{
21           private string _applicationName;
22           private SqlConnection sqlcon;
24           public override void Initialize(string name, NameValueCollection config)
25           {
26               base.Initialize(name, config);
27           }
29           public override string ApplicationName {
30   			get { return _applicationName; }
31   			set { _applicationName = value; }
32           }
34           public override void AddUsersToRoles(string[] usernames, string[] roleNames)
35           {
36               return;
37           }
39           public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
40           {
41               return;
42           }
44           public override void CreateRole(string roleName)
45           {
46               return;
47           }
49           public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
50           {
51               return true;
52           }
54           public override bool IsUserInRole(string username, string roleName)
55           {
56               SqlDataReader reader = runsql("SELECT * FROM usersinroles WHERE username LIKE '" + username + "' AND role LIKE '" + roleName + "'");
57               Boolean hasrows = reader.HasRows;
58               reader.Close();
59               sqlcon.Close();
61               if (hasrows)
62                   return true;
63               else
64                   return false;
65           }
67           public override bool RoleExists(string roleName)
68           {
69               SqlDataReader reader = runsql("SELECT * FROM roles WHERE name LIKE '" + roleName + "'");
70               Boolean hasrows = reader.HasRows;
71               reader.Close();
72               sqlcon.Close();
74               if (hasrows)
75                   return true;
76               else
77                   return false;
78           }
80           public override string[] GetRolesForUser(string username)
81           {
82               SqlDataReader reader = runsql("SELECT role FROM usersinroles WHERE username LIKE '" + username + "'");
83               string[] blah = getstringfield(reader, "role");
84               sqlcon.Close();
85               return blah;
86           }
88           public override string[] GetAllRoles()
89           {
90               SqlDataReader reader = runsql("SELECT name FROM roles");
91               string[] blah = getstringfield(reader, "name");
92               sqlcon.Close();
93               return blah;
94           }
96           public override string[] GetUsersInRole(string roleName)
97           {
98               SqlDataReader reader = runsql("SELECT username FROM usersinroles WHERE role LIKE '" + roleName + "'");
99               string[] blah = getstringfield(reader, "username");
100              sqlcon.Close();
101              return blah;
102          }
104          public override string[] FindUsersInRole(string roleName, string usernameToMatch)
105          {
106              SqlDataReader reader = runsql("SELECT username FROM usersinroles WHERE username LIKE '%" + usernameToMatch + "%' AND role LIKE '" + roleName + "'");
107              string[] blah = getstringfield(reader, "username");
108              sqlcon.Close();
109              return blah;
110          }
112          private SqlDataReader runsql(string sql)
113          {
114              this.sqlopen();
115              SqlCommand cmd = new SqlCommand(sql, this.sqlcon);
116              SqlDataReader reader = cmd.ExecuteReader();
117              return reader;
118          }
120          private string[] getstringfield(SqlDataReader reader, string col)
121          {
122              IList<string> roleNames = new List<string>();
123              while (reader.Read())
124                  roleNames.Add(reader[col].ToString());
125              string[] roles = new string[roleNames.Count];
126              roleNames.CopyTo(roles, 0);
127              reader.Close();
128              return roles;
129          }
130          private void sqlopen()
131          {
132              this.sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MIIS_AuthorizationConnectionString"].ConnectionString.ToString());
133              this.sqlcon.Open();
134          }
135          private void sqlclose()
136          {
137              this.sqlcon.Close();
138          }
139      }
140  }
7/18/2008 7:17:00 AM 27051 articles. 1 followers. Follow

5 Replies

Similar Articles

[PageSpeed] 2
Get it on Google Play
Get it on Apple App Store


Have you specified applicationName property for RoleManager? I saw some people solved this problem and shared the answer:


Best Regards
XiaoYong Dai
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.
7/22/2008 3:08:16 AM

I found that thread the day after posting, i tryed it and its not helping.

 When i set an

<authorization> tag on a specifick page, or on the whole application, i always get the windows login form.


So absically i have 2 problems:

1- role provider is not working

2- i'm not redirected to a custom error page


Any ideas what i can try?

7/22/2008 6:55:15 AM

 i was getting the same problem and found that the best way to sort it out was to use the role provider code, so add a page where everyone has access, then try to add users, add roles, then add users to roles, then start validating with the provider. Dont just let it run off and do it though, step through all the procedures, thats where i found issues with mine, the application names where different only by a character, I've also seen others that had differences in the role names where it was adding extra spaces in the database...

7/22/2008 8:38:51 AM

will now it seems that the role provider is working perfectly,

 the only problem was that the username that was stored in the db was just the login name, but since i'm using windows authentication the username that was used to request data was domain\username. So there was never a match found => no access.

7/22/2008 9:25:48 AM

 yeh nice its along those lines that i got caught out 2...



Big Smile 

7/22/2008 11:18:06 AM

Similar Artilces:

Custom Membership and Custom Role Provider Problems
I've built a Custom Membership Provider and Custom Role Provider, and am having a few troubles. I've built on top of a custom database structure. The relevant tables are: UserLogin: UserName, Password, Active, PasswordQuestion, PasswordAnswer UserRole: RoleID, RoleName User_Role: Username, RoleID (an association table) I've also built classes to manage these tables, including a SystemUser class, a UserRole class, and aggregate classes to handle the relationships. I'm not 100% certain, but an fairly confident from a handful of tests that these classes and the database are working as expec...

Having problem to implement --- Custom Membership Provider & Role Provider
Hi guys, there are many interesting posts in this security thread to implement the custom membership provider & role provider. It helps me a lot. But I m having a problem to implement it. I've got the loging page - Login.aspx and create new user page - CreateNewUser.aspx. And a Membership Provider class - clsMembershipProvider.vb in App_Code folder. The codin inside the Membership Provider Class - clsMembershipProvider.vb is as follow: Imports Microsoft.VisualBasic     Imports SystemImports System.WebImports System.Web.SecurityImports System.Configuration.Provide...

Problem implementing a Custom Role Provider.
Hello Everyone,       Im having some trouble trying to implement a custom role provider into my web application.  I have compiled the library file with the source code provided from the msdn article.. I placed the library file into the bin folder as directed but im getting an error inside the web configuration file.. <roleManager defaultProvider="CustomRoleProvider"         enabled="true">       <providers>       &nb...

problems with custom providers
I have created custom providers for both membership and roles. I created them in a separate VB.NET project. The relevant snippets from my Web.config: <connectionStrings> <clear/> <add name="VelinsConnectionString" connectionString="Data Source=GARTH;Initial Catalog=VelocityInsurance;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings> <roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="VelinsRoleProvider" cookieT...

Problem implementing Custom Role Provider
I am using VS2005 and i m Implementing Custom Membership and Role Provider. My Custom Membership provider is working fine but Role provider is not Below is my Web.config file and the error that comes If i dont remove "<allow roles='a'/> in Web.config file. I am retrieveing usertype from "LoginMaster" table and returning it as user role in custom role provider class GetRolesForUser() Method. Web.config---------------------------------------------------------------------------------------<?xml version="1.0"?><!-- Note: As an alternative to ...

Problem on using Custom Role Provider
I've already searched the forum regarding this but I can't get an answer in VB code and exact details.. I've already get the idea on how to create the custom membership provider but I can't understand the how to use a custom role provider. I've already put the ff codes on my web.config<roleManager enabled="true" defaultProvider="Class2">        <providers>          <add name="Class2"          connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=C:...

sql server reporting services 2005 SQL Membership Provider need to implement Roles Provider.
I have an internet facing SSRS that I have implemented the SQL Member provider using the ASP.NET 2.0 SQL Membership Provider and the using one of the SQL Server 2005 server samples Reporting Services  Reporting Services\Extension Samples\FormsAuthentication Sample   and modified to use the SQL Membership provider  as written in this article... it works well but does not telegraph the the SSRS.  My Issue is: I need to implement the role provider in this configuration ...does anyon...

AJAX.NET in a custom module : Some kinda security problem
I have been building a custom module which uses the AJAX.NET dll (available through: have it working very well for ROOT portals, but for some reason it is breaking on CHILD Portals??Here's what I've done to make it work:In web.config I had to add the httpHanlder:<add verb="POST,GET" path="controls/*.ashx" type="Ajax.PageHandlerFactory, Ajax" />I used the path "controls/*.ashx" to get around DNNs URL Rewriting.  Using this path, DNN doesn't try to re-write the URL.  (By the way if you've been having problems gettin...

Problems implementing role security (.Net 1.1)
I'm having a problem implementing role based security.  Here's my code:   Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) ' Fires upon attempting to authenticate the use If Not HttpContext.Current.User Is DBNull.Value Then If HttpContext.Current.User.Identity.AuthenticationType = "Forms" Then Dim id As Web.Security.FormsIdentity = CType(HttpContext.Current.User.Identity, Web.Security.FormsIdentity) Dim ticket As Web.Security.FormsAuthenticationTicket = id.Ticket Dim userData As String = ticket.User...

Problem with Login control using custom role providers
Hi,         I am using login control in my dafault page which will speak to my custom  membership and role providers for authentication. I Havent write any code in login page and still after i click on login it is hitting my custom membership provider.So far so good Now the problem is i need that to speak to my role provider and depending on the role of the user i want to redirect to different pages .I tried to dynamically set the destination page url its not working. Am i missing something or is the way i am doing that is wrong?. Please help with...

Issue with Role Based Security with Sql SiteMap Provider
Hi,In our project we are using SqlSiteMap provider concept to implement dynamic menus. For this, we have created one class (SiteMapProvider.cs), which is derived from StatisSiteMapProvider. We have created our own database table and by using Dictionary concept we are keeping values which we got from database. Actually, we have to implement roll based security here. i.e. for administrator only, Admin tab should visible. For all other users, Admin tab shouldnt be visible. We are using Dictionary and we are storing values on the dictionary object after user login. But, we are unable to clear th...

Using .net Security & Roles in SQL 2000 on the internet
I am working on setting up ASP.Net Security & Roles on a website hosted by GoDaddy.  My site is using the SQL 2000 server.  I have my code working on my laptop using SQL 2000 Server.  What I need to know is how do I create roles in the Sql 2000 server tables, which is hosted by GoDaddy?  I have successfully created roles using the Visual Studio ASP.Net Configuration page, but this only configures my local SQL server, not the one on Godaddy.  Any suggestions would be greatly appreciated.   David Hi This article might help: Remote Membership/Roles Manag...

.net 3.5 Custome Role Provider Redirect on Access Denied
I built a cutome role provider for authentication on my companies new web site and it works. the only issue i am having is when it encounters a resource the user does not have access to it gives a generic "page cannot be displayed" page. i tried adding some custome error pages for http error 401 in the web.config but it hasnt had any luck. something i read leads me to believe the role provider is actually denying access well before asp gets that far to even do the redirect. i also havent had much luck researching this so if there is a good article or maybe a tip i would appreciat...

Strange problem of newly added roles not being able to log in (custom membership provider)
Hi, I am having a very frustrating problem!When I add a new role and user to my ASP.NET membership scheme, it is not being granted access to the secure section of my site. I don't get any error messages, the page seems to flicker like it is refreshing, and the login boxes just go blank. It does detect if I enter in details incorrect.To test it I created a user in an existing role that I set up initially that works. No problem. I then create a new role and give it access to the secure section of my site, and when I move the user into the new role, no luck.I am using a custom membership pr...

Web resources about - custom sql role provider problem -

Providers - Wikipedia, the free encyclopedia
Jeppe Federspiel and Rasmus Stabell started as musicians playing drums. Years later, they joined forces to form Providers, an urban production ...

Provider - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Google Purchases Wildfire, A Facebook Marketing Software Provider
... search engine is working to change that. Google has purchased Wildfire , which helps businesses master Facebook, the marketing software provider ...

KGI expects Apple to sell 2.5M iPad Pros in Q4 as TSMC found to be sole provider of A9x chip
... in January, although it’s unclear if it will breakdown iPad Pro numbers specifically. Also of note, Kuo shares that TSMC is the sole provider ...

Doctors are physicians, not "care-providers." If your doctor does things by the book, then he/she is not focusing on you. Dr. Accad wrote a ...

Town that has no cell phone service loses its primary Internet provider
... and aside from satellite, the town had just one option for anything resembling modern Internet access. Unfortunately, that broadband provider ...

Pacific Controls Is Recognised Among ‘50 Most Promising IoT Solution Providers 2015’ by CIOReview Magazine ...
Pacific Controls is recognised among &lsquo;50 Most Promising IoT Solution Providers 2015&rsquo; by CIOReview magazine

Report: Juniper Is Eating Cisco's Lunch In U.S. Service Provider Routing Market
Report: Juniper Is Eating Cisco's Lunch In U.S. Service Provider Routing Market CRN Juniper Networks appears to be on a comeback in the U.S. ...

Starbucks Cup Evangelist Called For Assassination Of Abortion Providers
You can call this video what you want, but I'll call it terrorism. It's no different than when ISIS threatens to behead journalists, and it isn't ...

Foxconn invests in smartphone-rental service provider in Hong Kong, says paper
FIH Mobile, a subsidiary of the Foxconn Group, has recently invested US$13 million in Hong Kong-based handset rental service provider Tink Labs, ...

Resources last updated: 12/4/2015 6:27:20 AM