Ayesha
Ayesha

Reputation: 905

Windows authentication using database and C# (MVC)

I have a database table where all the company employees are listed. They have roles (a, b, c) defined to each employee. for e.g. employee 1 has role a, employe 2 has role b and so on.

Now, i want to check if employe has either of the 3 roles. if yes, provide that user access to website. if no roles mentioned to that user, deny access. The c# code should be able to take the windows login information and then query the database.

can anyone please let me know how to use C# code and start off with things

Upvotes: 1

Views: 1806

Answers (1)

Bewar Salah
Bewar Salah

Reputation: 567

A Filter Attribute that extends AuthorizeAttribute. It gets the roles for the user in the database and compares with the roles assigned to each controller or method.

public class UserRoleAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //Data Repository. Getting data from database
        var repository = new LoginRoleRepository();
        //GetCharacterSeparator is an Extension method of String class
        //It seperates the comma separated roles.
        //The data comes from the controller
        var roles = Roles.GetCharacterSeparator(',', true);

        if (httpContext.User.Identity.IsAuthenticated)
        {
            //Here I check if the user is in the role, you can have your own logic. The data is gotten from DB.
            var userRoles =
                repository.All().Where(obj => obj.Login.Username == httpContext.User.Identity.Name).Single().Roles;


            foreach (var role in roles)
                if (userRoles.Any(obj => obj.Name == role))
                    return true;
        }
        return false;
    }
}

Then you just define the attribute for each method or controller as bellow.

//Both Doctors and Receptionist have access to Patient controller.
[UserRoleAuthorize(Roles="Doctors, Receptionist")]
public class PatientController : Controller
{
     //Both Doctors and Receptionist have access to Schedule an appointment for patients.
     public ActionResult Schedule()
     {
            return View();
     }

     //Only Doctors have access to Treat patients.
     [UserRoleAuthorize(Roles="Doctors")]
     public ActionResult TreatPatient()
     {
            return View();
     }
}

You need to add extra information as:

//Here seperate the roles as Doctor:ReadWrite, Receptionist:Read
//If you see Doctor:ReadWrite means the doctor has Read and Write and so on.
//This code is in AuthorizeCore
var roles = Roles.GetCharacterSeparator(',', true);

//And Add the bellow to the controllers and methods.
[UserRoleAuthorize(Roles="Doctors:Write, Employees:Read")]

Upvotes: 2

Related Questions