【问题标题】:ASp.net Role management in Identity 2.0Identity 2.0 中的 ASp.net 角色管理
【发布时间】:2016-05-11 18:02:29
【问题描述】:

我有一个使用 ASp.net Identity 2 身份验证的网站项目。 我可以登录网站,注册新用户,运行到目前为止构建的应用程序页面。 但是我需要添加角色管理,所以我可以按用户限制功能。 事实证明,尝试自己学习它非常困难。 我的 Asp.net 4.5 书(Murach 的 ASP.NET 4.5 Web Programming with C# 2012)说“使用网站管理工具” 你可能已经知道,MS 已经淘汰了。 无论如何,我发现的几种尝试实现它的方法都失败了。

因此,我开始为此构建自己的管理页面。 到目前为止,它很简单,很丑陋,并且部分功能仍然无法正常工作。我就是不知道为什么。

这里附上我的整个 Web.config(为安全而编辑),以及添加角色的相关代码隐藏。到目前为止的测试代码将添加一个角色,然后尝试将其分配给我的用户 ID。

角色似乎已创建,但我不知道在哪里...它不会出现在我数据库的 [dbo].[AspNetRoles] 表中。我说似乎,因为当我再次尝试时,查看角色是否存在的测试会跳闸并说它已经存在。 if (!Roles.RoleExists(newRoleName)) { Roles.CreateRole(newRoleName); } // 结束创建新角色 项目数据文件夹中没有数据库。

System.Web.Providers。显然是新的标准类和 “这些通用提供程序很可能会成为 ASP.NET 下一版本的默认设置。”我听见。 我分配了正确的数据库连接字符串。 显然仍然缺少一些东西,我正在继承一些我只是不知道在某处寻找的默认值......

任何提示或提示表示赞赏。 甚至是后来的书。

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>

代码隐藏

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
    }
}

就是这样 告诉你这只是一个开始... 尚未创建编辑功能

【问题讨论】:

    标签: c# asp.net .net


    【解决方案1】:

    web.config 被配置为旧的 ASP.Net Membership Provider。

    但是,代码是 ASP.Net Identity 和旧的 ASP.Net Membership Provider 的组合。

    请免费阅读 Adam Freeman 的 ASP.Net Identity at Apress

    【讨论】:

    • 感谢您的评论。我知道,该文档中的示例也是 MVC。我对 MVC 一无所知,所以我不确定哪些部分不适用于 Web 窗体。示例 Web.config 中几乎没有与我相同的内容,它最初是在我创建项目时由 VS 构建的。我不知道为什么它会插入冲突的身份信息。我真正添加的唯一部分是角色提供程序。
    • ASP.Net Identity 不使用提供者模型,这就是您在 web.config 中看不到的原因。网站管理工具不能用于 ASP.Net 身份。如果您想查看示例代码,您可以在 Visual Studio 2015 中创建一个新的 Web 窗体应用程序。逻辑与 Adam Freeman 的 MVC 几乎相同。
    • Ahhhhhhh......看,这就是为什么有时使用教程会让你感到厌烦......如果它们有点过时了,他们当然不知道。好的,我需要更新我的 MSDN,愚蠢的东西上周过期了,我们的地方可能有点慢,无法获得文书工作......然后我可以得到 2015,重新开始。 :-( 我希望标准构建项目启用角色。2013 年的新网站特别提到它已被禁用,然后将您引导到 MVC 示例以了解如何启用它。可悲的是,对我来说几乎没用。MVC 在我无法翻译的形式和功能。
    • 好的,所以,2015 年构建的新项目看起来与 2013 年的项目完全相同。我现在才知道成员资格和身份是两个不同的东西。 VS 默认配置中的注释“在此模板中禁用 ASP.NET 成员资格”引导我添加提供程序代码。我仍然不知道如何处理身份中的角色,但我想我知道从配置中删除什么。
    猜你喜欢
    • 2014-10-28
    • 1970-01-01
    • 2018-12-27
    • 2014-12-25
    • 2016-10-24
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多