How best to override the authentication in MVC 5? - c#

I have a project in which does not have registration. Administrator registers users in admin. The project does not have the roles, I have only one type of user. I do not need "AspNetRoles", "AspNetUserClaims", "AspNewUserLogins", "AspNetUserRoles". And in the table "AspNetUsers" I need only "Id", "Email", "Password" and a few custom properties. What is the best way to implement this in mvc 5?

To Add more columns/fields to AspNetUsers you need to add those in Identity Model adn do Data Migration using -update database command
you can also control the Keys and Table Name by Overriding as below
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<IdentityUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
modelBuilder.Entity<ApplicationUser>().ToTable("MyUsers").Property(p => p.Id).HasColumnName("UserId");
modelBuilder.Entity<IdentityUserRole>().ToTable("MyUserRoles");
modelBuilder.Entity<IdentityUserLogin>().ToTable("MyUserLogins");
modelBuilder.Entity<IdentityUserClaim>().ToTable("MyUserClaims");
modelBuilder.Entity<IdentityRole>().ToTable("MyRoles");
}
When you are using ASPNET Schema for user registration, I don't think you can avoid Claims,Roles and other tables, but you can just ignore those.
Update
In order to avoid Roles and Claims in ASPNET membership
First of all create a MVC 5 application. Then implement IUser,
public class ApplicationUser : IUser
{
public ApplicationUser()
{
this.Id = Guid.NewGuid().ToString();
}
public ApplicationUser(string userName): this()
{
UserName = userName;
}
public virtual string Id { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string SecurityStamp { get; set; }
public virtual string UserName { get; set; }
}
Next we need a DbContet to store the Users,
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
public virtual IDbSet<ApplicationUser> Users { get; set; }
}
and then we need to implement IUserStore, IUserPasswordStore and IUserSecurityStampStore,
public class MyUserStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>, IUserSecurityStampStore<ApplicationUser>
{
UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(new ApplicationDbContext());
public MyUserStore()
{
}
public Task CreateAsync(ApplicationUser user)
{
var context = userStore.Context as ApplicationDbContext;
context.Users.Add(user);
context.Configuration.ValidateOnSaveEnabled = false;
return context.SaveChangesAsync();
}
public Task DeleteAsync(ApplicationUser user)
{
var context = userStore.Context as ApplicationDbContext;
context.Users.Remove(user);
context.Configuration.ValidateOnSaveEnabled = false;
return context.SaveChangesAsync();
}
public Task<ApplicationUser> FindByIdAsync(string userId)
{
var context = userStore.Context as ApplicationDbContext;
return context.Users.Where(u => u.Id.ToLower() == userId.ToLower()).FirstOrDefaultAsync();
}
public Task<ApplicationUser> FindByNameAsync(string userName)
{
var context = userStore.Context as ApplicationDbContext;
return context.Users.Where(u => u.UserName.ToLower() == userName.ToLower()).FirstOrDefaultAsync();
}
public Task UpdateAsync(ApplicationUser user)
{
var context = userStore.Context as ApplicationDbContext;
context.Users.Attach(user);
context.Entry(user).State = EntityState.Modified;
context.Configuration.ValidateOnSaveEnabled = false;
return context.SaveChangesAsync();
}
public void Dispose()
{
userStore.Dispose();
}
public Task<string> GetPasswordHashAsync(ApplicationUser user)
{
var identityUser = ToIdentityUser(user);
var task = userStore.GetPasswordHashAsync(identityUser);
SetApplicationUser(user, identityUser);
return task;
}
public Task<bool> HasPasswordAsync(ApplicationUser user)
{
var identityUser = ToIdentityUser(user);
var task = userStore.HasPasswordAsync(identityUser);
SetApplicationUser(user, identityUser);
return task;
}
public Task SetPasswordHashAsync(ApplicationUser user, string passwordHash)
{
var identityUser = ToIdentityUser(user);
var task = userStore.SetPasswordHashAsync(identityUser, passwordHash);
SetApplicationUser(user, identityUser);
return task;
}
public Task<string> GetSecurityStampAsync(ApplicationUser user)
{
var identityUser = ToIdentityUser(user);
var task = userStore.GetSecurityStampAsync(identityUser);
SetApplicationUser(user, identityUser);
return task;
}
public Task SetSecurityStampAsync(ApplicationUser user, string stamp)
{
var identityUser = ToIdentityUser(user);
var task = userStore.SetSecurityStampAsync(identityUser, stamp);
SetApplicationUser(user, identityUser);
return task;
}
private static void SetApplicationUser(ApplicationUser user, IdentityUser identityUser)
{
user.PasswordHash = identityUser.PasswordHash;
user.SecurityStamp = identityUser.SecurityStamp;
user.Id = identityUser.Id;
user.UserName = identityUser.UserName;
}
private IdentityUser ToIdentityUser(ApplicationUser user)
{
return new IdentityUser
{
Id = user.Id,
PasswordHash = user.PasswordHash,
SecurityStamp = user.SecurityStamp,
UserName = user.UserName
};
}
}
For password hash and security stamp, I am using the UserStore's implementation for making thing simpler. Finally we just need to change AccountController's constructor to leverage our MyUserStore implementation,
public AccountController()
: this(new UserManager<ApplicationUser>(new MyUserStore()))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
To Drop unnecessary columns in Users Table. You can try somethign like this
public partial class ModifyUser: DbMigration
{
public override void Up()
{
AddColumn("dbo.AspNetUsers", "NewField", c => c.String());
}
public override void Down()
{
DropColumn("dbo.AspNetUsers", "NewColumn");
}
}
Then in packageManager run PM> update-database

Related

ASP.NET Core Web API - Put action with DTO didn't update the existing object

I've been trying to write Put (update) action without the id property, by using DTO. But every time I'm trying I'm getting the existing object and not the updated one, and I can't figure out why and how to change it so it will work.
My repository:
public User Update(Guid id, User user)
{
var userToUpdate=_context.Users.FirstOrDefault(x => x.Id == id);
_context.Entry(userToUpdate).State = EntityState.Modified;
_context.SaveChanges();
return userToUpdate;
}
My DTO:
public class UserPostDTO
{
public UserPostDTO()
{
}
public UserPostDTO(User user)
{
UserName= user.UserName;
Password= user.Password;
LastLogin= user.LastLogin;
}
[StringLength(255)]
public string UserName { get; set; } = null!;
[StringLength(255)]
public string Password { get; set; } = null!;
[Column(TypeName = "datetime")]
public DateTime? LastLogin { get; set; }
public User ToPostUser()
{
var user = new User();
user.UserName = UserName;
user.Password = Password;
user.LastLogin = LastLogin;
return user;
}
}
My Controller:
public class UserController : ControllerBase
{
private readonly IUserRepository _userRepository;
public UserController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
[HttpPut("{id}")]
public IActionResult Put(Guid id, [FromBody] UserPostDTO user)
{
_userRepository.Update(id, user.ToPostUser());
return Ok();
}
Didn't see you updating the User object with the new value.
Probably this is what you need:
public User Update(Guid id, User user)
{
var userToUpdate = _context.Users.FirstOrDefault(x => x.Id == id)
.AsNoTracking();
if (userToUpdate == null)
{
// Handle ID is not existed
throw new ArgumentNullException("ID is not existed");
}
user.Id = userToUpdate.Id;
_context.Entry(user).State = EntityState.Modified;
_context.SaveChanges();
return user;
}

How to make autogenerated Guid as ID primary key in ApiAuthorizationDbContext IdentityDbContext instead of string

In ASP.NET Core 6 Web API, I have:
ApplicationUser model class:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MobileNumber { get; set; }
}
This is the ApplicationUserConfiguration:
public class ApplicationUserConfigurations : IEntityTypeConfiguration<ApplicationUser>
{
public void Configure(EntityTypeBuilder<ApplicationUser> builder)
{
builder.HasIndex(u => u.Email).IsUnique();
builder.HasIndex(u => u.UserName).IsUnique();
builder.Ignore(u => u.AccessFailedCount);
builder.Ignore(u => u.LockoutEnabled);
builder.Ignore(u => u.TwoFactorEnabled);
builder.Ignore(u => u.ConcurrencyStamp);
builder.Ignore(u => u.LockoutEnd);
builder.Ignore(u => u.EmailConfirmed);
builder.Ignore(u => u.TwoFactorEnabled);
builder.Ignore(u => u.AccessFailedCount);
builder.Ignore(u => u.PhoneNumberConfirmed);
}
}
public interface IApplicationDbContext
{
public DbSet<Merchant> merchants { get; set; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
}
I use ApiAuthorizationDbContext. This is the ApplicationDbContext:
public class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser>, IApplicationDbContext
{
private readonly IDateTime _dateTime;
private readonly ICurrentUserService _currentUserService;
private readonly IDomainEventService _domainEventService;
public ApplicationDbContext(
DbContextOptions options,
IOptions<OperationalStoreOptions> operationalStoreOptions,
ICurrentUserService currentUserService,
IDateTime dateTime,
IDomainEventService domainEventService) : base(options, operationalStoreOptions)
{
_dateTime = dateTime;
_domainEventService = domainEventService;
_currentUserService = currentUserService;
}
public DbSet<Merchant> zib_merchants { get; set; }
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
foreach (EntityEntry<AuditableEntity> entry in ChangeTracker.Entries<AuditableEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = _currentUserService.UserId;
entry.Entity.CreatedAt = _dateTime.Now;
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = _currentUserService.UserId;
entry.Entity.LastModifiedAt = _dateTime.Now;
break;
}
}
var result = await base.SaveChangesAsync(cancellationToken);
await DispatchEvents();
return result;
}
protected override void OnModelCreating(ModelBuilder builder)
{
ConfigureDecimalPrecision(builder);
builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
base.OnModelCreating(builder);
builder.ApplyConfiguration(new ApplicationUserConfigurations());
builder.ApplyConfiguration(new MerchantConfigurations());
}
}
Program.cs:
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();
if (context.Database.IsSqlServer())
{
await context.Database.MigrateAsync();
}
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
ApplicationDbContextSeed.SeedData(userManager, roleManager);
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while migrating or seeding the database.");
throw;
}
}
await host.RunAsync();
}
When I ran the migration, I found that each of the Id of AspNetUsers, AspNetRoles etc are string - nvarchar(450).
How do I make AspNetUsers, AspNetRoles and AspNetUserRoles use autogenerated GUIDs instead?
Thanks
It seems, you have also "IdentityUser" class. So change Id line to:
[Key]
public Guid Id { get; set; }
and also add the following line in "ApplicationUserConfigurations.cs" and "ApplicationRolesConfigurations.cs".
builder.HasKey(x => x.Id);

Pass user detail after Login Is successful From identity asp.net core 3.1

I was wondering how to pass user detail when the user sign response is 200. I'm using Asp.net core identity, here is my code for httpPost controller for authentication :
It only sends username when user login with response 200.
namespace Test.Controllers
{
[Route("/api/authentication/")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly UserManager<User> userManager;
private readonly SignInManager<User> signInManager;
public AuthenticationController(UserManager<User> userManager, SignInManager<User> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[HttpPost("login")]
public async Task<ActionResult<UserDTO>> Login(LoginDTO dto)
{
var user = await userManager.FindByNameAsync(dto.UserName);
if (user == null)
{
return BadRequest();
}
var password = await signInManager.CheckPasswordSignInAsync(user, dto.Password, true);
if (!password.Succeeded)
{
return BadRequest();
}
await signInManager.SignInAsync(user, false, "Password");
return Ok(new UserDTO { UserName = user.UserName });
}
[HttpPost("logout")]
public async Task<ActionResult> logout()
{
await signInManager.SignOutAsync();
return Ok();
}
}
}
I want to get all the user information not only userName that is in UserDTO.cs when user signIn with response 200.
namespace Test.Features.Users
{
public class UserDTO
{
public string UserName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
public string Role { get; set; }
}
}
Here is my create account controller
namespace Test.Controllers
{
[Route("api/createaccount")]
[ApiController]
public class CreateAccountController : ControllerBase
{
private readonly DataContext dataContext;
private readonly SignInManager<User> signInManager;
private readonly UserManager<User> userManager;
public CreateAccountController(DataContext dataContext, SignInManager<User> signInManager, UserManager<User> userManager)
{
this.dataContext = dataContext;
this.signInManager = signInManager;
this.userManager = userManager;
}
[HttpPost]
public async Task<ActionResult<UserDTO>> CreateUser(CreateAccountDTO dto)
{
var newuser = new User
{
UserName = dto.UserName,
Email = dto.Email,
PhoneNumber = dto.PhoneNumber,
};
using (var transaction = await dataContext.Database.BeginTransactionAsync())
{
var identityresults = await userManager.CreateAsync(newuser, dto.Password);
if (!identityresults.Succeeded)
{
return BadRequest();
}
var roleresults = await userManager.AddToRoleAsync(newuser, Roles.Customer);
if (!roleresults.Succeeded)
{
return BadRequest();
}
transaction.Commit();
await signInManager.SignInAsync(newuser, isPersistent: false);
var user = await userManager.FindByEmailAsync(newuser.Email);
var rolesList = await userManager.GetRolesAsync(user);
var getRole = rolesList[0];
Console.WriteLine(getRole);
return Created(string.Empty, new UserDTO
{
UserName = newuser.UserName,
Email = newuser.Email,
PhoneNumber = newuser.PhoneNumber,
Password = newuser.PasswordHash,
Role = getRole
}) ;
}
}
}
}
for role
i have role.cs and roles.cs
namespace Test.Features.Roles
{
public class Roles
{
public const string Admin = nameof(Admin);
public const string Customer = nameof(Customer);
private static bool HasAnyRole(ClaimsPrincipal user, string target)
{
foreach(var role in target.Split(","))
{
if (user.IsInRole(role))
{
return true;
}
}
return false;
}
}
}
namespace Test.Features.Roles
{
public class Role:IdentityRole<int>
{
public virtual ICollection<UserRole> Users { get; set; } = new List<UserRole>();
}
}
thank you!
So you need to use the UserManager for this. If you look at what i am returning, this is what you want. I have tested this and it works my end. Any questions let me know.
For the roles, a user can have multiple roles and the method below returns a list of roles.
var roles = await _userManager.GetRolesAsync( test );
So your UserDTO will look like the below:
public class UserDTO
{
public string UserName { get; set; }
public string Email { get; set; }
public string PhoneNumber { get; set; }
public string Password { get; set; }
public List<string> Role { get; set; }
}
And your controller method will look like the below:
[Route("/api/authentication/")]
[ApiController]
public class AuthenticationController : ControllerBase
{
private readonly UserManager<User> userManager;
private readonly SignInManager<User> signInManager;
public AuthenticationController(UserManager<User> userManager, SignInManager<User> signInManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
}
[HttpPost("login")]
public async Task<ActionResult<UserDTO>> Login(LoginDTO dto)
{
var user = await userManager.FindByNameAsync(dto.UserName);
var roles = await _userManager.GetRolesAsync( user );
if (user == null)
{
return BadRequest();
}
var password = await signInManager.CheckPasswordSignInAsync(user, dto.Password, true);
if (!password.Succeeded)
{
return BadRequest();
}
await signInManager.SignInAsync(user, false, "Password");
return Ok(new UserDTO { UserName = user.UserName, Email = user.Email, PhoneNumber = user.PhoneNumber, Password = user.PasswordHash, Role = roles.ToList() });
}

How to give custom implementation of UpdateAsync method of asp.net identity?

I am doing custom asp.net identity and not using asp.net inbuilt tables.I have successfully created user with implementing custom CreateAsync
Now i want to update user with new encrypted password and so i am not getting how to provide custom implementation of UpdateAsync method.
This is my table:
User : Id,Name,EmailId,Password,Statistics,Salary
Model:
public class UserModel : IUser
{
public string Id { get; set; }
public string Name { get; set; }
public string EmailId { get; set; }
public string Password { get; set; }
public int Salary { get; set; }
}
My custom class which implements IUserstore:
public class UserStore : IUserStore<UserModel>, IUserPasswordStore<UserModel>
{
private readonly MyEntities _dbContext;
private readonly HttpContext _httpContext;
// How to implement this method for updating only user password
public Task UpdateAsync(UserModel user)
{
throw new NotImplementedException();
}
public Task CreateAsync(UserModel user)
{
return Task.Factory.StartNew(() =>
{
HttpContext.Current = _httpContext ?? HttpContext.Current;
var user = _dbContext.User.Create();
user.Name = user.Name;
user.EmailId = user.EmailId;
user.EmailAddress = user.Email;
user.Password = user.Password;
_dbContext.Users.Add(dbUser);
_dbContext.SaveChanges();
});
}
public Task SetPasswordHashAsync(UserModel user, string passwordHash)
{
return Task.Factory.StartNew(() =>
{
HttpContext.Current = _httpContext ?? HttpContext.Current;
var userObj = GetUserObj(user);
if (userObj != null)
{
userObj.Password = passwordHash;
_dbContext.SaveChanges();
}
else
user.Password = passwordHash;
});
}
public Task<string> GetPasswordHashAsync(UserModel user)
{
//other code
}
}
Controller:
public class MyController : ParentController
{
public MyController()
: this(new UserManager<UserModel>(new UserStore(new MyEntities())))
{
}
public UserManager<UserModel> UserManager { get; private set; }
[HttpPost]
public async Task<JsonResult> SaveUser(UserModel userModel)
{
IdentityResult result = null;
if (userModel.Id > 0) //want to update user with new encrypted password
result = await UserManager.UpdateAsync(user);
else
result = await UserManager.CreateAsync(userModel.EmailId, userModel.Password);
}
}
Not sure if this is what your looking for...
public Task UpdateAsync(UserModel model)
{
var user = _dbContext.User.Find(x => x.id == model.id);
user.Password = model.Password;
_dbContext.SaveChanges();
return Task.CompletedTask;
}
It Will get the specific record and Update the password and then save the record.
Edit
Since the password is not getting encrypted i added code to take that string and leave the model as it is, this extension method will encrypt the value of password, i have not test this but i am sure it will work.
user.Password = model.Password.EncryptPassword(EncryptKey);
Extension methods to encrypt password
Sometime back, I created a complete wrapper over .NET Identity and code can be found here. It might be helpful for you. You can also find nuget here. I also explained the library in a blog here.

Property or indexer 'IdentityUser<int, ApplicationUserLogin,ApplicationUserRole,ApplicationUserClaim>.Roles' cannot be assigned to -- it is read only

I'm working on MVC5 with Identity 1.0 Entity Framework web application. In my seed method I'm trying to assign roles to my user during the first migration.
I get an error when I put
Role = "Admin"
Property or Indexer 'IdentityUserApplicationUserLogin,ApplicationUserRole,ApplicationUserClaim>.Roles' cannot be assigned to -- it is read only
Does this mean I have to assign the role manually on the website when I run the application?
Configuration.cs
var roles = new List<ApplicationRole>
{
new ApplicationRole { Id = 1, Name = "Admin"},
new ApplicationRole { Id = 2, Name = "User"},
};
roles.ForEach(s => context.Roles.AddOrUpdate(p => p.Name, s));
context.SaveChanges();
var passwordHash = new PasswordHasher();
string password = passwordHash.HashPassword("Password#123");
var users = new List<ApplicationUser>
{
new ApplicationUser { UserName = "jackie#hotmail.com", FirstMidName = "Jackie", LastName = "Chan", Email="jasonw#rs.kiwi.nz",PasswordHash = password, Roles = "Admin",
EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1,IsAdministrator = true,SecurityStamp = Guid.NewGuid().ToString()},
users.ForEach(s => context.Users.AddOrUpdate(p => p.UserName, s));
context.SaveChanges();
IdentityModel.cs
namespace RecreationalServicesTicketingSystem.Models
{
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
public string Description { get; set; }
public ApplicationRole() : base() { }
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, string description)
: this(name)
{
this.Description = description;
}
}
public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
public async Task<ClaimsIdentity>
GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
{
var userIdentity = await manager
.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
public bool IsAdministrator { get; set; }
[StringLength(50, MinimumLength = 1)]
public string LastName { get; set; }
[StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
[Column("FirstName")]
public string FirstMidName { get; set; }
public string FullName
{
get { return FirstMidName + " " + LastName; }
}
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EnrollmentDate { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int DepotID { get; set; }
[ForeignKey("DepotID")]
public virtual Depot Depot { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
static ApplicationDbContext()
{
Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public DbSet<Ticket> Tickets { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Depot> Depots { get; set; }
}
public class ApplicationUserStore :
UserStore<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUserStore<ApplicationUser, int>, IDisposable
{
public ApplicationUserStore()
: this(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationUserStore(DbContext context)
: base(context)
{
}
}
public class ApplicationRoleStore
: RoleStore<ApplicationRole, int, ApplicationUserRole>,
IQueryableRoleStore<ApplicationRole, int>,
IRoleStore<ApplicationRole, int>, IDisposable
{
public ApplicationRoleStore()
: base(new IdentityDbContext())
{
base.DisposeContext = true;
}
public ApplicationRoleStore(DbContext context)
: base(context)
{
}
}
}
Roles Controller
namespace RecreationalServicesTicketingSystem.Controllers
{
//[Authorize(Roles = "Admin")]
public class RolesAdminController : Controller
{
public RolesAdminController()
{
}
public RolesAdminController(ApplicationUserManager userManager,
ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
}
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
set
{
_userManager = value;
}
}
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
//
// GET: /Roles/
public ActionResult Index()
{
return View(RoleManager.Roles);
}
//
// GET: /Roles/Details/5
public async Task<ActionResult> Details(int id)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
// Get the list of Users in this Role
var users = new List<ApplicationUser>();
// Get the list of Users in this Role
foreach (var user in UserManager.Users.ToList())
{
if (await UserManager.IsInRoleAsync(user.Id, role.Name))
{
users.Add(user);
}
}
ViewBag.Users = users;
ViewBag.UserCount = users.Count();
return View(role);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//
// GET: /Roles/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Roles/Create
[HttpPost]
public async Task<ActionResult> Create(RoleViewModel roleViewModel)
{
if (ModelState.IsValid)
{
// Use ApplicationRole, not IdentityRole:
var role = new ApplicationRole(roleViewModel.Name);
var roleresult = await RoleManager.CreateAsync(role);
if (!roleresult.Succeeded)
{
ModelState.AddModelError("", roleresult.Errors.First());
return View();
}
return RedirectToAction("Index");
}
return View();
}
//
// GET: /Roles/Edit/Admin
public async Task<ActionResult> Edit(int id)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
if (role == null)
{
return HttpNotFound();
}
RoleViewModel roleModel = new RoleViewModel { Id = role.Id, Name = role.Name };
return View(roleModel);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//
// POST: /Roles/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "Name,Id")] RoleViewModel roleModel)
{
if (ModelState.IsValid)
{
var role = await RoleManager.FindByIdAsync(roleModel.Id);
role.Name = roleModel.Name;
await RoleManager.UpdateAsync(role);
return RedirectToAction("Index");
}
return View();
}
//
// GET: /Roles/Delete/5
public async Task<ActionResult> Delete(int id)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
if (role == null)
{
return HttpNotFound();
}
return View(role);
}
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//
// POST: /Roles/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(int id, string deleteUser)
{
if (ModelState.IsValid)
{
if (id > 0)
{
var role = await RoleManager.FindByIdAsync(id);
if (role == null)
{
return HttpNotFound();
}
IdentityResult result;
if (deleteUser != null)
{
result = await RoleManager.DeleteAsync(role);
}
else
{
result = await RoleManager.DeleteAsync(role);
}
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
return View();
}
}
}
The roles property of your new ApplicationUser object expects an iCollection of ApplicationUserRole items. See example below.
new ApplicationUser
{
UserName = "jackie#hotmail.com",
FirstMidName = "Jackie",
LastName = "Chan",
Email = "jasonw#rs.kiwi.nz",
PasswordHash = password,
Roles =
{
new ApplicationUserRole
{
RoleId = 1
}
},
EnrollmentDate = DateTime.Parse("2016-02-18"),
DepartmentID = 1,
DepotID = 1,
IsAdministrator = true,
SecurityStamp = Guid.NewGuid().ToString()
}

Categories

Resources