Stargate_Forever
Stargate_Forever

Reputation: 21

ASp.net Role management in Identity 2.0

I have a web site project using ASp.net Identity 2 authentication. I can log-in to the site, register new users, run the application pages built so far just fine. But I need to add Role management, so I can limit functionality by user. This is proving amazingly difficult to do trying to learn it on your own. My Asp.net 4.5 book (Murach’s ASP.NET 4.5 Web Programming with C# 2012) says "Use the Web Site Administration Tool" Which you probably already know, MS has eliminated. The several methods I have found to try to get to it anyway have failed miserably.

So, I started building my own Admin page for this. So far it is simple, ugly, and parts of it still don't work. And I just don't know why.

Attached here is my entire Web.config (edited for security), and what is the pertinent code-behind for adding a role. The test code so far will Add a role, and then attempt to assign it to My user ID.

The Role Seems to get created, but I have no idea Where... It does Not end-up in the [dbo].[AspNetRoles] table in my database. I say seems, because when I try again, the test to see if the role exists trips and says it's there already. if (!Roles.RoleExists(newRoleName)) { Roles.CreateRole(newRoleName); } // End create new role There is NOT a database in the project Data folder.

System.Web.Providers. is apparently the new, standard Class and "it's very likely that these Universal Providers will be the default in the next version of ASP.NET." I hear. I have the correct DB connection strings assigned. Clearly there is still Something missing, and I am inheriting some default that I just don't know to look for, somewhere...

Any hints or tips appreciated. Even a later book.

Web.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <!--<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Parts-20160425083953.mdf;Initial Catalog=aspnet-Parts-20160425083953;Integrated Security=True" providerName="System.Data.SqlClient" />-->
    <add name="PartsDatabase" connectionString="Data Source=-redacted-;Initial Catalog=-mydatabasename-;User ID=--dbuserID--;Password=--thepassword--" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="emailServiceUserName" value="--emailuserid--" />
    <add key="emailServicePassword" value="--emailPW--" />
  </appSettings>
  <system.web>
    <!--<authentication mode="None" />-->
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="60" protection="All" slidingExpiration="true">
      </forms>
    </authentication>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
        <add namespace="Microsoft.AspNet.Identity" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
    <membership defaultProvider="ASPNetMembershipProvider">
      <providers>
        <clear />
        <!--<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />-->
        <add name="ASPNetMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <profile defaultProvider="ASPNetProfileProvider">
      <providers>
        <clear />
        <!--<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />-->
        <add name="ASPNetProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" applicationName="/" />
      </providers>
    </profile>
    <roleManager defaultProvider="ASPNetRoleProvider" enabled="true">
      <providers>
        <clear />
        <!--<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />-->
        <add name="ASPNetRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" applicationName="/" />
      </providers>
    </roleManager>
    <sessionState mode="InProc" customProvider="ASPNetSessionProvider">
      <providers>
        <!--<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />-->
        <add name="ASPNetSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="PartsDatabase" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

Code-behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using Sperry_Parts.Models;

namespace Parts.Account
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var signinManager = Context.GetOwinContext().GetUserManager<ApplicationSignInManager>();

            gvUsers.DataSource = manager.Users.ToList();
            gvUsers.DataBind();
        }

-- Code-behind for the Add Role button --
        protected void btnAddRole_Click(object sender, EventArgs e)
        {
            string newRoleName = txtRole.Text.Trim();
            if (!Roles.RoleExists(newRoleName)) 
            {
                Roles.CreateRole(newRoleName); // This works once per new Role - where it Goes is anyone's guess
            } // End create new role


            // Check Users in Roles
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            var user = manager.FindByName("myusername");
            string username = user.UserName; // properly returns "myusername"
            if (Membership.GetUser("myusername") != null) // Fails - returns Null
                if (!Roles.IsUserInRole(user.UserName, newRoleName)) // Without the above check, this returns False, I'm not in this role... (natch)
                    Roles.AddUserToRole(user.UserName, newRoleName); // This fails, can't find the user

        } // End Add Role
    }
}

That's it Told you it was just a start... Editing capability has not been created yet

Upvotes: 2

Views: 1028

Answers (1)

Win
Win

Reputation: 62260

web.config is configured as old ASP.Net Membership Provider.

However, code is the combination of ASP.Net Identity and old ASP.Net Membership Provider.

Please read free ASP.Net Identity at Apress by Adam Freeman.

Upvotes: 1

Related Questions