简体   繁体   中英

Roles asp.net settings

I'm currently developing an app with ASP.NET MVC 4 , but I`am also learning.

I want to use Roles, for authentication, but something I`am doing wrong.

The point is that I dont need more roles, I just want the default one.

<system.web>

<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<roleManager enabled="true" />

At controller

[Authorize(Roles = "Administrator")]
public class AccountController : Controller
{}

And in the LogIn post method I want to add user to that role.

if (!Roles.IsUserInRole(saveAccount.Username, "Administrators"))
     Roles.AddUserToRole(saveAccount.Username, "Administrators");

But everytime I LogIn and try to redirect to another page I get this

HTTP Error 401.0 - Unauthorized You do not have permission to view this directory or page.

Can someone guide me, please?

When adding a user to a role, you have to use the UserId, not the username.

You also have to create a record in the Roles table with the name of the role you desire.

Use RoleManager to create a new role.

        ApplicationDbContext context = new ApplicationDbContext();
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

        if (!roleManager.RoleExists("Admin"))
        {

            //Creating Admin role  
            var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
            role.Name = "Administrator";
            roleManager.Create(role);
        }

        if (!Roles.IsUserInRole(#yourUserId, "Administrator")) {
            Roles.AddUserToRole(#yourUserId, "Administrator");
        }

(The database for your users and roles is under DefaultConnection in the Data Connections area within Server Explorer).

Roles is Authorization, Authentication is another process.

If your need is just to restrict on known users, then :

  • Create a login view with user/pass
  • Implemente Forms authentication on web.config section <system.web>
  • Deny anonymous users

.

<system.web>
    <compilation debug="true" targetFramework="4.6.1" />
    <httpRuntime targetFramework="4.6.1" />
    <authentication mode="Forms">
             <forms all parameters needed to a connection's forms></forms>
    </authentication>
    <authorization>
      <deny users="?" />
    </authorization>
</system.web>

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