Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple custom roles for windows authentication in asp. net?

At our company network, the roles in Active Directory(AD) are not appropriately assigned for my application. So I created a simple table in my database mapping all the users in the AD and their roles. There is literally only two columns in this table, user and role.

I hope to take advantage of the powerful role management in asp.net, I want to use features like [Authorize(Roles = "Managers")]. is there a simple way to use these custom roles without setting up complicated role and membership provider?

application background: sql server, linq, asp.net mvc

like image 647
Bonk Avatar asked Apr 27 '12 22:04

Bonk


People also ask

How do you implement Windows Authentication How do you specify roles and permissions to the users?

To set up your ASP.NET application to work with Windows-based authentication, begin by creating some users and groups. Within your Windows operating system, go to "Control Panel" -> "User Accounts" -> "Manage another account" -> "Create a new account" then choose "Add or Remove User".

How do I configure Windows Authentication in web config?

On the taskbar, click Start, and then click Control Panel. In Control Panel, click Programs and Features, and then click Turn Windows Features on or off. Expand Internet Information Services, then World Wide Web Services, then Security. Select Windows Authentication, and then click OK.

How can create role based authentication in ASP NET MVC?

Open Visual Studio 2015 or an editor of your choice and create a new project. Choose "web application" project and give an appropriate name to your project. Select "empty" template, check on the MVC box, and click OK. Right-click on the Models folder and add a database model.


2 Answers

It is really easy to implement custom role provider. Basically you will need to implement two functions.

Look at the article: Custom Role Provider for MVC

like image 57
Igor Avatar answered Sep 18 '22 21:09

Igor


Article provided in the event the website goes down.

Custom Role Provider for MVC

In a previous article, I explain how to create Custom Membership Provider to authorize the user and protect controls and pages. But what if you want to show or protect some area, controller or page for a specific group of users? For example, allow access to Admin Panel only for admins.

In .Net Framework for this purpose is Role Provider. But again, it uses own DB for store user roles. So let's create and configure Custom Role Provider which will use our DB or any other storage. As before we should overwrite class from .NET:

enter image description here

enter image description here

enter image description here

For the minimum functionality, we need implement and overwrite two functions GetRolesForUser and IsUserInRole. First, one is used to get a list of all user roles (or groups):

public override string[] GetRolesForUser(string username)
{
    using (DatabaseEntities db = new DatabaseEntities())
    {
        User user = db.Users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase) || u.Email.Equals(username, StringComparison.CurrentCultureIgnoreCase));

        var roles = from ur in user.UserRoles
                    from r in db.Roles
                    where ur.RoleId == r.Id
                    select r.Name;
        if (roles != null)
            return roles.ToArray();
        else
            return new string[] {}; ;
    }
}

As you can see I locate the user in my DB by username parameter of the function (in my case it’s can be username or email) and create the string list of user roles.

Second function is to check if user in the role (or group):

public override bool IsUserInRole(string username, string roleName)
{
    using (DatabaseEntities db = new DatabaseEntities())
    {
        User user = db.Users.FirstOrDefault(u => u.UserName.Equals(username, StringComparison.CurrentCultureIgnoreCase) || u.Email.Equals(username, StringComparison.CurrentCultureIgnoreCase));

        var roles = from ur in user.UserRoles
                    from r in db.Roles
                    where ur.RoleId == r.Id
                    select r.Name;
        if (user != null)
            return roles.Any(r => r.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
        else
            return false;
    }
}

Then we need to configure in web.config file solution to use created role provider. May need to set cacheRolesInCookie to false for debugging purposes or behavior will be unpredictable.

<system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <authentication mode="Windows" />
    <authorization>
        <deny users="?" />
    </authorization>
    <roleManager cacheRolesInCookie="true" defaultProvider="KitsulaRoleProvider" enabled="true">
        <providers>
            <clear />
            <add name="KitsulaRoleProvider" type="Kitsula.Security.KitsulaRoleProvider" />
        </providers>
    </roleManager>
</system.web>

Now you can protect controllers, actions, pages for a specific group of users which are in specified roles by set Authorize attribute:

using System;
using System.Web.Mvc;

namespace Kitsula.Areas.Admin.Controllers
{
    [Authorize(Roles = "Administrators")]
    public class HomeController : Controller
    {
        //
        // GET: /Admin/Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}
like image 26
Jack Avatar answered Sep 20 '22 21:09

Jack