asp.net MVC 5 Role management, authorization error “No user was found”

Hello,

I’m new to asp.net MVC 5, so i excuse if i’m asking stupid question or something, but i’ve tried to make it on my own, but i couldn’t. So currently i’m working on a mvc 5 project and i have to add roles, so i followed this tutorial:

http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

Then i made the roles, i clear fast everything, when the problem came. Everything works fine except a few thing, which i fixed. Only one problem left, when i authorize some sections, for example:

> [Authorize(Roles = "Admin")]

> public ActionResult Create()

Only administrators to be allowed to create news, and then when i logged in as an administrator and try to create something, the following comes:

> "No user found was found that has the name "user1@contoso.com"."
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: No user found was found that has the name "user1@example.com".

Any help will be very usefull,

Thanks

Could you post the code that you are using?

Generally, if you are trying to add a user to a Role, you’ll first want to actually retrieve the user and then use their "ID" to add them to the role :

// Examples of accessing User / Role Managers
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); 
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

// Find your user
var user = userManager.FindByName("user1@contoso.com");

// Ensure your user was found
if(user != null)
{
       // The user was not found, do something
       return HttpNotFound();
}
else
{
       // The user was found, so add them to the role

       // Ensure your role exists
       if (roleManager.RoleExists("YourRoleName"))
       {
              userManager.AddToRole(user.Id, "YourRoleName");
       }
}

Yes, of course, this is my RolesController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PublicWebMongolia.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace PublicWebMongolia.Controllers
{
    public class RolesController : Controller
    {
        
        ApplicationDbContext context = new ApplicationDbContext();

        //
        // GET: /Roles/
        public ActionResult Index()
        {
            var roles = context.Roles.ToList();
            return View(roles);
        }

        //
        // GET: /Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Roles/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                context.Roles.Add(new Microsoft.AspNet.Identity.EntityFramework.IdentityRole()
                {
                    Name = collection["RoleName"]
                });
                context.SaveChanges();
                ViewBag.ResultMessage = "Role created successfully !";
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Roles/Edit/5
        public ActionResult Edit(string roleName)
        {
            var thisRole = context.Roles.Where(r => r.Name.Equals(roleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            return View(thisRole);
        }

        //
        // POST: /Roles/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Microsoft.AspNet.Identity.EntityFramework.IdentityRole role)
        {
            try
            {
                context.Entry(role).State = System.Data.Entity.EntityState.Modified;
                context.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Roles/Delete/5
        public ActionResult Delete(string RoleName)
        {
            var thisRole = context.Roles.Where(r => r.Name.Equals(RoleName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            context.Roles.Remove(thisRole);
            context.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult ManageUserRoles()
        {
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;            
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RoleAddToUser(string UserName, string RoleName)
        {            
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            //var account = new AccountController(); ne raboti s dolniq red syzdaveme nova instanciq
            //account.UserManager.AddToRole(user.Id, RoleName);
            // var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            //var idResult = um.AddToRole(user.Id, RoleName);
            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var idResult = um.AddToRole(user.Id, RoleName);
            ViewBag.ResultMessage = "Role created successfully !";
            
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;   

            return View("ManageUserRoles");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult GetRoles(string UserName)
        {            
            if (!string.IsNullOrWhiteSpace(UserName))
            {                                
                ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
                //var account = new AccountController();
                var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
                ViewBag.RolesForThisUser = um.GetRoles(user.Id);
                
                                
                // prepopulat roles for the view dropdown
                
                var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
               
                ViewBag.Roles = list;            
            }

            return View("ManageUserRoles");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteRoleForUser(string UserName, string RoleName)
        {
           // var account = new AccountController();
            ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            if (um.IsInRole(user.Id, RoleName))  
            {
                um.RemoveFromRole(user.Id, RoleName);
                ViewBag.ResultMessage = "Role removed from this user successfully !";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }
            // prepopulat roles for the view dropdown
            var list = context.Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
            ViewBag.Roles = list;

            return View("ManageUserRoles");
        }
    }
}

And just to add:

// When i authorize with [Authorize(Users = "user1@contoso.com")], actually it works, but when i authorize with roles, i receive the error..

Are you sure that you have a role that matches the one being specified? And that there are no typos related to it?

Yes, I’m sure:

Here’s an image: http://postimg.org/image/aw63r9hdj/full/

I’ve made role canEdit, add the user to this role, and then i authorized the actionmethod to canEdit roles only, and still doesn’t work…

Should i add something in my web.config file for the roles? Maybe there’s the error.

Thank you for the support once again..

And you are using the following attribute to decorate your actions?

[Authorize(Roles = "canEdit")]

If that is the case, the only thing that I can think of is that your existing Authorize attribute is somehow being overridden or your current user simply isn’t authenticated and is being denied access because of it.

madlyyy

Should i add something in my web.config file for the roles? Maybe there’s the error.

Not really. If you are using the updated ASP.NET Identity Model (that relies on UserManager and RoleManager objects), then it should handle most of the creation and management of Roles for you (without any extra web.config work).

 // GET: News/Edit/5
        [Authorize(Roles = "canEdit")]
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            News news = db.News.Find(id);
            if (news == null)
            {
                return HttpNotFound();
            }
            return View(news);
        }

        // POST: News/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "canEdit")]
        public ActionResult Edit([Bind(Include = "NewsId,Title,Information,Active,DataCreating,DataExpired")] News news)
        {
            if (ModelState.IsValid)
            {
                db.Entry(news).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(news);
        }

Yes, i’m using this attribute.. and the current user which i’m using in the image is authenticated.. 

Thank you once again, maybe i will find the error those days ;)

Edit:/// I solve the problem: just add in global.asax

 void Application_PostAuthenticateRequest()
        {
            if (User.Identity.IsAuthenticated)
            {
                var name = User.Identity.Name;
                // do your DB lookup here
                if (name == Context.User.Identity.Name)
                {
                    var roles = new string[] { "admin", "canEdit" };
                    HttpContext.Current.User =
                        Thread.CurrentPrincipal =
                        new GenericPrincipal(User.Identity, roles);

                }
            }
        }

Leave a Reply