2015-12-13 3 views
0

Я работаю над созданием системы ролей в ASP.net. Теперь он отлично работает, потому что я могу связать роли с пользователямиРолевая авторизация в ASP.net MVC 4

Как вы можете видеть здесь.

AspNetUserRoles

Теперь мой вопрос, что я должен сделать, чтобы получить доступ на основе ролевой рабочим. Потому что это как-то не работает. Он посылает меня в качестве супер администратора обратно на страницу входа

[Authorize(Roles = "Superadmin")] 
    public ActionResult Upload() 
    { 
     return View(); 
    } 

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> 
    <!-- 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="MyConString" connectionString="server=JENSJONKMAN\SQLEXPRESS; database=JensGoesASP; integrated security=true;"/>--> 
    <add name="DefaultConnection" connectionString="Data Source=JENSJONKMAN\SQLEXPRESS;  Initial Catalog=JensGoesASP;Integrated Security=True" providerName="System.Data.SqlClient" /> 
    <add name="JensGoesASPEntities" connectionString="metadata=res://*/ImageModel.csdl|res://*/ImageModel.ssdl|res://*/ImageModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=JENSJONKMAN\SQLEXPRESS;initial catalog=JensGoesASP;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> 
    </connectionStrings> 
    <appSettings> 
    <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="None" /> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 
    </system.web> 
    <system.webServer> 
    <modules> 
     <remove name="FormsAuthenticationModule" /> 
    </modules> 
    </system.webServer> 
    <runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <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.0.0.0" newVersion="5.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="WebGrease" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" /> 
     <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" /> 
     <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.SqlConnectionFactory, EntityFramework" /> 
    <providers> 
     <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> 
    </providers> 
    </entityFramework> 
</configuration> 

Я надеюсь, что кто-то может мне помочь.

Greetz

+0

Вы создали таблицы Сеть САШ на вашем SQL с использованием aspnet_regsql.exe (C: \ Windows \ Microsoft.NET \ Framework64 \ v4.0.30319 \ aspnet_regsql.exe) или это то, что вы сами построили сами? – learningcs

+0

Нет Я не использовал aspnet_regsql.exe. Я добавил строку подключения к моему проекту, а затем таблицы были автоматически созданы в моей базе данных. Но я могу просто добавить роли в свою базу данных и изменить их. – Swolschblauw

+0

Показать связанную конфигурацию в web.config. Я считаю, что вам нужно указать поставщика роли, чтобы он работал. – mason

ответ

1

Вы должны добавить роли в UserPrincipal в Global.asax файле

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; 

    if (authCookie != null) 
    { 
     FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); 
     // Read the roles from cookie 
     string[] roles = authTicket.UserData.Split(new Char[] { ',' }); 

     GenericPrincipal userPrincipal = new GenericPrincipal(new GenericIdentity(authTicket.Name), roles); 
     Context.User = userPrincipal; 
    } 
} 

Создание настраиваемого Authorize атрибут и переопределить OnAuthorization методу

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    // Check if the user is authorized to access else redirect to unauthorized page 
    base.OnAuthorization(filterContext); 
} 
+0

Спасибо, это отлично работает для меня! – Swolschblauw

Смежные вопросы