簡體   English   中英

自定義角色提供程序未使用

[英]Custom Role Provider Not Being Used

好吧,所以我為我的網站創建了一個自定義角色提供程序,無論我做什么,我都無法從覆蓋函數中獲取代碼來獲得成功。

這是自定義角色提供者

namespace XXX.Security
{
    using System;
    using System.Linq;
    using XXX.Areas.AccountManagement;
    using System.Web.Security;

    public class AppRoleProvider : RoleProvider
    {
        public override string ApplicationName
        {
            get
            {
                throw new NotImplementedException();
            }

            set
            {
                throw new NotImplementedException();
            }
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override void CreateRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            throw new NotImplementedException();
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            throw new NotImplementedException();
        }

        public override string[] GetAllRoles()
        {
            AccountManagementDbContext accountManagement = new AccountManagementDbContext("App Role Provider - GetAllRoles()");

            string[] roles = accountManagement.getRoles();

            return roles;
        }

        public override string[] GetRolesForUser(string username)
        {
            AccountManagementDbContext accountManagement = new AccountManagementDbContext("App Role Provider - GetRolesForUser()");

            string[] userRoles = accountManagement.getRolesForUser(username);

            return userRoles;
        }

        public override string[] GetUsersInRole(string roleName)
        {
            throw new NotImplementedException();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            AccountManagementDbContext accountManagement = new AccountManagementDbContext("App Role Provider - GetAllRoles()");

            string[] userRoles = accountManagement.getRolesForUser(username);

            return userRoles.Contains(roleName);
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            throw new NotImplementedException();
        }

        public override bool RoleExists(string roleName)
        {
            throw new NotImplementedException();
        }
    }
}

這是我的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=301880
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
    <add name="xxx"
         providerName="System.Data.SqlClient"
         connectionString="Data Source=xxx;
                           Initial Catalog=xxx;
                           Integrated Security=false;
                           User ID=xxx;
                           Password=xxx;"/>
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="EnableSimpleMembership" value="false" />
  </appSettings>
  <system.web>
    <authentication mode="Windows" />
    <roleManager defaultProvider="AppRoleProvider" enabled="true">
      <providers>
        <clear/>
        <add name="AppRoleProvider" type="xxx.Security.AppRoleProvider"/>
      </providers>
    </roleManager>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="System.Data.SqlServerCe.4.0" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
      <provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SqlServerCe.4.0" />
      <add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </DbProviderFactories>
  </system.data>
</configuration>

這是我正在使用的自定義授權屬性

namespace XXX.Models
{
    using System.Web;
    using System.Web.Mvc;

    public class AccessDeniedAuthorizationAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            var user = HttpContext.Current.User.Identity.Name;

            if (filterContext.Result is HttpUnauthorizedResult)
            {               
                filterContext.Result = new RedirectResult("/AccessDenied");
            }
        }
    }
}

最后這是我的控制器

namespace XXX.Areas.Admin.Controllers
{
    using Models;
    using System.Web.Mvc;

    public class AdminController : Controller
    {
        [AccessDeniedAuthorization(Roles = "Administrator")]
        public ActionResult AdminHome()
        {
            var user = HttpContext.User.Identity.Name;
            return View();
        }
    }
}

因此,我嘗試了一些方法來使其正常工作...

在控制器操作上使用默認的Authorize屬性進行了嘗試。

試圖在我的web.config中為提供者指定其他屬性,例如...

  <system.web>
    <authentication mode="Windows" />
    <roleManager defaultProvider="AppRoleProvider" enabled="true">
      <providers>
        <clear/>
        <add name="AppRoleProvider" type="XXX.Security.AppRoleProvider, XXX" connectionStringName="XXX"/>
      </providers>
    </roleManager>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
  </system.web>

我已經從控制器中訪問了角色提供程序中所有重寫的函數,以確保它們正常工作並且都正常工作並達到了我在其中的斷點。 當我在自定義的Authorization屬性中放置一個斷點時,盡管該斷點在調用Admin控制器中的控制器動作時命中。 我什至查看了HttpContext.Current.User.ProviderName,它是我的自定義角色提供程序的名稱。

另一件事很奇怪,就是我的User.Identity在應使用Windows登錄信息填充時從未填寫,因此我可以想象這一定是Windows身份驗證無法正常工作的問題。

我的項目屬性中也打開了Windows身份驗證。 我還啟用了匿名身份驗證,因為我需要同時使用兩種身份驗證。

也要把它扔在那里。 我的自定義角色提供程序在我的Web項目中,但是它引用的acccountmanagementdbcontext在一個單獨的項目中,盡管我看不到這會引起任何問題。

**更新**我在搜尋有關更改IIS express的applicatonhost.config文件時發現了一些東西。

<windowsAuthentication enabled="true">
    <providers>
        <add value="Negotiate" />
        <add value="NTLM" />
    </providers>
</windowsAuthentication>

我做到了,但仍然行不通。

** Update 2 **似乎由於某種原因,用戶必須至少輸入一次Windows憑據才能使Windows身份驗證能夠對其進行身份驗證。 我在本地運行時使用Windows憑據嘗試了此操作,輸入憑據后,便擊中了自定義角色提供程序中的代碼。

我的印象是,如果打開了Windows身份驗證,並且將請求發送到需要身份驗證的控制器/操作,則它只會自動提取Windows用戶的憑據,然后將其傳遞給角色提供者。

我的老板說,如果您與IIS服務器位於同一網絡上,它將自動獲取Windows用戶的憑據,但是我對此表示懷疑,因為我嘗試將其托管在IIS中的主機名中,並將其dns地址保存在IIS中的PC上而且它仍然沒有自動將Windows憑據自動填充到HttpContext.User.Identity中。

您必須使用Internet Explorer才能在站點開始時自動進行Windows身份驗證。 如果您使用IE訪問站點,則將使用當前的Windows用戶名填充HttpContext.User.Identity.Name屬性。 我當時使用的是Firefox。 這也就是為什么我認為在我按下該控制器操作時未填充該屬性是不正確的原因。 在除IE以外的任何瀏覽器中,當您嘗試訪問您受限制的站點區域時,必須打開Windows身份驗證,然后在彈出的登錄框中輸入Windows憑據。 我禁用了該登錄彈出窗口,因此在我的站點中,當我嘗試訪問設置為受限的控制器操作時,它從未通過Windows驗證,因為如果不在該彈出窗口登錄名中輸入Windows憑據,則不會填充Identity.Name。 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM