Ada sangat sedikit dokumentasi tentang menggunakan baru Asp.net Identitas Kerangka Keamanan.
Saya telah disatukan apa yang saya bisa untuk mencoba dan menciptakan Peran baru dan menambahkan Pengguna ke dalamnya. Saya mencoba yang berikut ini: https://stackoverflow.com/questions/19541101/add-role-in-asp-net-identity
yang terlihat seperti itu mungkin telah mendapat info dari blog ini: bangunan sederhana to-do aplikasi dengan asp.net identitas dan menghubungkan pengguna dengan ke-tidak
Saya telah menambahkan kode ke Database Initializer yang dijalankan setiap kali perubahan model. Gagal di RoleExists
fungsi dengan error berikut:
Sistem.InvalidOperationException
terjadi di mscorlib.dll Jenis entitas IdentityRole bukan bagian dari model untuk konteks saat ini.
protected override void Seed (MyContext context)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
// Create Admin Role
string roleName = "Admins";
IdentityResult roleResult;
// Check to see if Role Exists, if not create it
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
Setiap bantuan sangat dihargai.
Di sini kita pergi:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if(!roleManager.RoleExists("ROLE NAME"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "ROLE NAME";
roleManager.Create(role);
}
Berikut ini adalah artikel yang menjelaskan cara membuat peran, memodifikasi peran, menghapus peran dan mengelola peran menggunakan ASP.NET Identitas. Hal ini juga berisi User interface, controller metode dll.
http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc
Harapan ini helpls
Terima kasih
Dalam ASP.NET 5 rc1-final
, yang saya lakukan sebagai berikut:
Dibuat ApplicationRoleManager
(dalam cara yang sama seperti yang ada ApplicationUser
yang dibuat oleh template)
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(
IRoleStore<IdentityRole> store,
IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
ILogger<RoleManager<IdentityRole>> logger,
IHttpContextAccessor contextAccessor)
: base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
{
}
}
Untuk ConfigureServices
di Startup.cs
, saya menambahkan ini sebagai RoleManager
services.
.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<ApplicationRoleManager>();
Untuk menciptakan Peran baru, panggilan dari Configure
berikut ini:
public static class RoleHelper
{
private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
{
// add all roles, that should be in database, here
await EnsureRoleCreated(roleManager, "Developer");
}
}
public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
...
await roleManager.EnsureRolesCreated();
...
}
Sekarang, aturan dapat diberikan ke pengguna
await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");
Atau digunakan dalam Otorisasi
atribut
[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}
Sebagai perbaikan pada Peters kode di atas, anda dapat menggunakan ini:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));
Saya aplikasi tergantung pada startup ketika saya digunakan Peter Stulinski & Dave Gordon's kode sampel dengan EF 6.0. Aku berubah:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
untuk
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));
Yang masuk akal ketika dalam metode benih anda don't ingin instantiate contoh lain dari ApplicationDBContext
. Ini mungkin telah diperparah oleh fakta bahwa saya memiliki Database.SetInitializer<ApplicationDbContext>(baru ApplicationDbInitializer());
dalam konstruktor dari ApplicationDbContext
Peran Lihat Model
public class RoleViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "RoleName")]
public string Name { get; set; }
}
Metode Controller
[HttpPost]
public async Task<actionResult> Create(RoleViewModel roleViewModel)
{
if (ModelState.IsValid)
{
var role = new IdentityRole(roleViewModel.Name);
var roleresult = await RoleManager.CreateAsync(role);
if (!roleresult.Succeeded)
{
ModelState.AddModelError("", roleresult.Errors.First());
return View();
}
return RedirectToAction("some_action");
}
return View();
}
Saya ingin berbagi solusi lain untuk menambahkan peran:
<h2>Create Role</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
@Html.TextBox("RoleName", null, new { @class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}
Controller:
[HttpGet]
public ActionResult AdminView()
{
return View();
}
[HttpPost]
public ActionResult AdminView(FormCollection collection)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(collection["RoleName"]) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
}
return View();
}
metode yang saya Gunakan untuk menciptakan peran adalah di bawah ini, menugaskan mereka untuk pengguna di kode juga tercantum. kode di bawah ini tidak dapat di "konfigurasi.cs" dalam migrasi folder.
string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
IdentityResult roleResult;
foreach(var roleName in roleNames)
{
if(!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
UserManager.AddToRole("user", "role1");
UserManager.AddToRole("user", "role2");
context.SaveChanges();
Jika anda menggunakan template default yang dibuat ketika anda memilih baru ASP.net aplikasi Web dan dipilih masing-Masing akun Pengguna sebagai Otentikasi dan mencoba untuk membuat pengguna dengan Peran jadi di sini adalah solusinya. Dalam Akun Controller's Daftarkan metode yang disebut menggunakan [HttpPost], tambahkan baris berikut di jika kondisi
.
menggunakan Microsoft.AspNet.Identitas.EntityFramework;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!await roleManager.RoleExistsAsync("YourRoleName"))
await roleManager.CreateAsync(new IdentityRole("YourRoleName"));
await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
Ini akan membuat terlebih dahulu membuat peran dalam database anda dan kemudian menambahkan pengguna baru dibuat untuk peran ini.