简体   繁体   中英

Set AD Roles name on web.config

I'm developing an ASP.NET MVC 5 app with .NET Framework 4.5.1 and C#.

I'm using Windows authentication to allow some users to access my controllers. This is my web.config file:

<system.web>
  <compilation debug="true" targetFramework="4.5.1" />
  <httpRuntime targetFramework="4.5.1" />
  <authentication mode="Windows" />
  <authorization>
    <deny users="?" />
  </authorization>
  <roleManager enabled="true" defaultProvider="WindowsProvider">
    <providers>
        <clear />
        <add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
    </providers>
</roleManager>
</system.web>

And this is my Authorize attribute:

[Authorize(Roles = @"MyDomain\MyUploadRole")]
public class UploadController : Controller
{
   // ...
}

I want to add the string @"MyDomain\\MyUploadRole" to the web.config but I don't know how to do it.

I have tested this SO answer , but it doesn't work for me. I have added this part to web.config file:

<roles>
  <add key="Role1" value="MyDomain\MyUploadRole" />
  <add key="Role2" value="MyDomain\Another role" />
</roles>

And then, I change this on controller:

[Authorize(Roles = @"Role1")]
public class UploadController : Controller
{
   // ...
}

And Internet Explorer ask for my credentials, but I get unauthorized response.

How can I set role's name on web.config ?

May be this will work for you:

<configuration>    
<system.web>
    <authentication mode="Windows"/>
    <authorization>
     <allow roles="MyDomain\MyUploadRole"/>
     <deny users="?"/>
    </authorization>
    <identity impersonate="true"/>
</system.web>

And in your code you can check to see whether the user is in a role like this:

HttpContext.Current.User.IsInRole("MyDomain\MyUploadRole")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM