简体   繁体   中英

ASP.Net MVC 5 how to use Authorize Attribute with multiple login (Multiple user table)

I'm new to ASP.NET MVC 5. In the project I'm developing I have two user tables: one for clients and one for employees. I need to create two distinct login forms: one for clients and one for employees. The clients will have access to a particular part of the website, the employees will have access to another distinct part. Each part has its own actions. How can use the Authorize Attribute in order to distringuish clients from employees?

You can use the roles attribute for different types of users.

[Authorize(Roles="Users")]
public class UserController: Controller
{
}

[Authorise(Roles="Employees")]
public class EmployeeController: Controller
{
}


[Authorize(Roles = "User,Customer")]
public ActionResult RoleType()
{                        
    return View();
}

public class MyController : Controller
{
    private const string UserRole = "User";
    private const string EmployeeRole = "Employee";

    [Authorize(Roles = UserRole + "," + EmployeeRole)]
    public ActionResult UserOrEmployee()
    {                        
        return View();
    }
}

Only users that have that role now can access the controllers. Egthe employees controller can only be accessed by users whos role is of type "Employees" and the user controller can only be accessed by users of type role "User".

About creating different login forms, that won't be necessary at all. You can use one login form for both roles but depending on what you want either to see when logged in, you make use of User.IsInRole to verify and maybe redirect them or some other course action of your choice.

This is of course in addition to the answer provided by "The Akhemist".

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