简体   繁体   中英

C# MVC Simple Custom Authentication with Roles

TL;DR

EDit

Basically, I just want to tell to some function : Ok, I've checked this user my self, he's ok. Now store some arbitrary data about him and create a session for him that gives him permissions to access certain parts of my app.

something of this sort :

logInUserFrameworkFunction(new UserStruct(int id, string username, RolesEnum[] roles));

And than everything is handled in the background to make [Authorize(Roles = RolesEnum.Admin | RolesEnum.Manager)] attribute work.

I could make this with sessions my self but I would like to skip that part :D


I'm playing with MVC and Entity Framework, and now I'd like to implement simple user authentication with roles.

I have User class / table in my database that looks something like this :

public class User {
    int ID;
    string Email;
    string Password;
    Role Role;
...
}

And Role class that looks like this :

public class Role {
    int ID;
    RoleType Type; // this is an Enum
}

public Enum RoleType {
    visitor, employee, admin
}

Now, checking in login controller if user with specified username and password exists is easy, I just do something like this :

[HttpPost]
    public ActionResult LogIn(LogIn login) {
        // If credentials are valid
        if(new UserManager().IsValid(login.Username, login.Password)) {
            var user = db.getUserByEmail(login.Username);
...

I could easily store user ID and Role in session and than check credentials by calling some function on every relevant controller but I want to use some of C# and MVC features.


Thing is that I would rather do it with attributes, but I'm not sure how.

This is what I imagined it would look like :

[Roles(RoleType.visitor, RoleType.employee)]
public ActionResult SomeProtectedAction() {
// only employee and visitor can access this,
// others get redirected to where ever
...
}

You can authorize using Roles like this:

[Authorize(Roles= MyEnum.Admin | MyEnum.Moderator)]
public ActionResult myAction()
{
}

The Authorize attribute is here applied at controller level, but you can apply it only to action methods, depending on your needs.

Provided you have setup your authentication logic correctly (ASP.NET Identity) which will return an authentication cookie including user roles. Now after successful login, if you make a request to a controller method, the cookie is unpacked in the background and the User property this.User is filled with this data including roles of that user.

The authorize attribute will do the check for you automatically.

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