httpContext.User.Identity.Name Возвращается как «»

1

Я пытаюсь получить имя пользователя из моего приложения Windows MVC 5, прошедшего проверку подлинности, но строка продолжает возвращаться как "" или пустая. Я могу получить имя пользователя в моем контроллере, но при использовании этого нового класса я не могу его получить.

Вот мой код:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmployeeMaster.CustomAttribute;


namespace EmployeeMaster.CustomAttribute
{
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var username = httpContext.User.Identity.Name.Substring(httpContext.User.Identity.Name.IndexOf(@"\", StringComparison.Ordinal) + 1).ToUpper();
            return GetUserSecurityLevel(username);
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!AuthorizeCore(filterContext.HttpContext))
            {
                // If not authorized, redirect to the NotAuthorizedForApplication action 
                filterContext.Result = new RedirectToRouteResult(
                   new System.Web.Routing.RouteValueDictionary {
                   {"action", "NotAuthorizedForApplication"}
                }
                );
            }
        }

        private bool GetUserSecurityLevel(string username)
        {
            return true;
        }

    }
}

Вот моя веб-конфигурация:

<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>
  <appSettings>
    <add key="MailServer" value="mail2.pacificdda.com" />
    <add key="webpages:Version" value="3.0.0.0"/>
    <add key="webpages:Enabled" value="false"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>
  <system.web>
    <authentication mode="Windows" />
    <authorization>
      <allow users="?"/>
    </authorization>
    <compilation debug="true" targetFramework="4.0"/>
    <httpRuntime targetFramework="4.0"/>
    <customErrors mode="Off" />
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit"/>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"/>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0"/>
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
    </handlers>
    <modules>
      <remove name="UrlRoutingModule-4.0"/>
      <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition=""/>
      <remove name="Session"/>
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
      <remove name="BundleModule"/>
      <add name="BundleModule" type="System.Web.Optimization.BundleModule"/>
    </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-6.0.0.0" newVersion="6.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.5.2.14234" newVersion="1.5.2.14234"/>
      </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.WebPages" 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.0.0" newVersion="5.2.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <connectionStrings>
     </connectionStrings>
  <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>

Я видел сообщения, похожие на мои, но я пробовал общие вещи и не могу заставить их работать как на локальном хосте, так и на сервере.

Теги:
asp.net-mvc
asp.net-mvc-4
httpcontext

1 ответ

0

Проверьте свой авторизационный элемент в файле конфигурации.

<authorization>
  <allow users="?"/>
</authorization>

Это означает, что ваш сайт разрешает анонимным пользователям. Должен быть:

<authorization>
  <deny users="?"/>
  <allow users="*"/>
</authorization>

Сайт остановится на первом, чтобы оценить его как истинного, поэтому, если пользователь анонимен, им будет отказано в доступе, иначе они будут разрешены.

РЕДАКТИРОВАТЬ

Аутентификация работает, сначала отправив 401 в браузер, который определяет тип проверки подлинности. Это побуждает браузер запрашивать учетные данные. Узел авторизации в вашем web.config ИЛИ атрибуты авторизации на вашем контроллере - вот что подсказывает это. Если ваш web.config установлен для анонимных пользователей, то нет 401. Если нет 401, никакие учетные данные не будут отправлены, а Identity.Name будет пустым.

Вероятно, он работает в вашем контроллере, потому что вы включили AuthorizeAttribute.

  • 0
    Я получил 401.2 доступ запрещен
  • 0
    Вы также должны включить аутентификацию Windows в IIS Express и, возможно, закомментировать некоторый код. Для включения аутентификации Windows см. Следующий пост: stackoverflow.com/questions/4762538/… Код - app.UseCookieAuthentication в Startup.Auth.cs.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню