简体   繁体   中英

Custom role provider in ASP MVC

Hello i am kinda at lost here and i don't know what to fix:

The issue is that, my application still doesn't detect the roles assigned. Like if i have something like [Authorize(Roles="user")] . It won't detect my login and won't allow me to proceed on that view.

I've been following a bad tutorial and here's what i have to so far: (i want to make it first at least before i move on to another one)

Here are my database tables:

I didn't put any hash yet for simplicity:

Login table

在此处输入图片说明

roles table

在此处输入图片说明

I use inner join and i will have something like this

select A.username, A.role from login A INNER JOIN roles B on A.role = B.id

在此处输入图片说明

I use code first EF 4.0 and here are my code snippets:

I have a class roleprovider which inherits from roleprovider .

I only implemented 2 methods from it, namely: GetRolesForUser and IsUserInRole

GetRolesForUser

public override string[] GetRolesForUser(string uname)
    {
        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        {
            return null;
        }

        var cacheKey = string.Format("{0_role}", uname);
        if (HttpRuntime.Cache[cacheKey] != null)
        {
            return (string[])HttpRuntime.Cache[cacheKey];
        }

        string[] roles = new string[] { };
        using (EmployeeContext emp = new EmployeeContext())
        {
            roles = (from a in emp.login
                     join b in emp.roles on a.role equals b.id
                     where a.username.Equals(uname)
                     select b.role).ToArray<string>();
            if (roles.Count() > 0)
            {
                HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
            }
        }
        return roles;
    }

IsUserInRole

public override bool IsUserInRole(string uname, string roleName)
{
     var userRoles = GetRolesForUser(uname);
     return userRoles.Contains(roleName);
}

Web.Config

<roleManager>
  <providers>
    <clear/>
    <add name="roleprovider"  type="MvcApplication6.Helper.roleprovider"/>
  </providers>
</roleManager>

I apologize if i can't explain the code properly as of now because i am still in the process of learning it. My primary agenda as of now i to make the code work first but i am somehow lost because i am not particularly sure of what i am missing.

Recap of the issue: -Application won't detect the roles from the database and won't let me proceed if i try logging in.

edit: here is my login code( i have authentication mode implemented )

   [HttpGet]
    [ActionName("login")]
    public ActionResult login_load()
    {
        return View();
    }

    [HttpPost]
    [ActionName("login")]

    public ActionResult login_post(string uname,string pword)
    {
        using (EmployeeContext emp = new EmployeeContext())
        {

            int success = emp.login.Where(x => x.username == uname && x.password == pword).Count();
            if (success == 1)
            {
                FormsAuthentication.SetAuthCookie(uname, false);

                return RedirectToAction("Details", "Enrollment");
            }
            return View();
        }
    }

Some tips from looking at the code you posted.

Your web.config should look something like:

<roleManager enabled="true" defaultProvider="roleprovider">
  <providers>
    <clear/>
    <add name="roleprovider"  type="MvcApplication6.Helper.roleprovider"/>
  </providers>
</roleManager>

Ie you need to declare your custom roleprovider as the default provider.

You shold remove the following from your GetRolesForUser method:

if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
    return null;
}

The purpose of this method is to get the roles for the username passed as an argument - it shouldn't be concerned with the current user.

If this doesn't work, try putting a breakpoint in your GetRolesForUser method.

Solved the issue by fixing my Web.Config(then everything just worked magically). It wasn't working because messed up namespaces. Full credits to Joe for the idea.

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