Rafael Carrillo
Rafael Carrillo

Reputation: 2873

How to add roles to users in ASP.NET with OWIN

I'm new in ASP.NET and I'm making a simple project to practice. I started with a simple MVC project without authentication because it adds many code that I didn't understand.

But now I want to add a membership to my sistem so I followed this guide:

http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-1

http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-2

But I don't know where I can add a role to the user entity..

My Startup class is this:

public class Startup
    {
        public static Func<UserManager<Usuario>> UserManagerFactory { get; private set; }
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie"
            });
            UserManagerFactory = () =>
                {
                    var usermanager = new UserManager<Usuario>(new UserStore<Usuario>(new Vetpet3Context()));
                    usermanager.UserValidator = new UserValidator<Usuario>(usermanager)
                    {
                        AllowOnlyAlphanumericUserNames = false
                    };
                    return usermanager;
                };
        }
    }

And I'm creating (for now) my users with this Action:

[HttpPost]
        public async Task<ActionResult> Register(RegisterModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            var user = new Usuario
            {
                UserName=model.correo,
                correo = model.correo
            };
            var result = await userManager.CreateAsync(user, model.password);
            if (result.Succeeded)
            {
                await SignIn(user);
                return RedirectToAction("index", "Home");
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("", error);
            }

            return View();
        }

So everything works fine at this point, but I need to add different roles to the users , and this is the question, how I implement this part? I've read many guides but everyone does different things and I'm not sure how to add a role to my new users and how to claim these roles when they log in

Upvotes: 1

Views: 6816

Answers (1)

Eslam Hamouda
Eslam Hamouda

Reputation: 1151

to add role to the user after he successfully register :

if (result.Succeeded)
            {
                var roleResult = userManager.AddToRole(user.Id, "Admin");
                await SignIn(user);
                return RedirectToAction("index", "Home");
            }

to check if the user in role :

userManager.IsInRole(user.Id, "Admin");

or even simpler in any ASP.NET MVC [Authorized] controller :

User.IsInRole("roleName");

Upvotes: 4

Related Questions