Asp.net yadroidagi rollarni qanday yaratish va ularni foydalanuvchilarga tayinlash

Men asp.net yadrosi standart veb-sayt shablonini foydalanayapman va autentifikatsiya qilish alohida foydalanuvchi hisobi sifatida tanlangan. Raqamni qanday yarataman va foydalanuvchini unga filtrlash uchun auditorda rolni ishlatish uchun qanday qilib tayinlashim mumkin.

28
login paytida foydalanuvchi rollarini aniqlash uchun bilasizmi?
qo'shib qo'ydi muallif Yirga, manba

6 javoblar

Mening sharhlarim o'chirildi, chunki men shunga o'xshash savolga havola berdim, men javob berdi: "https://stackoverflow.com/questions/42188927/how-to-add-custom-roles-to-asp-net-core/ 42204984 # 42204984 "> bu yerda . Ergo, men bu safar batafsil javob beraman. Bu erda.

Buni boshlang'ich sinfida CreateRoles usulini yaratish orqali osonlik bilan amalga oshirish mumkin. Bu rollar yaratilganligini tekshirishga yordam beradi va ular bo'lmasa, rollarni yaratadi; ilovani ishga tushirishda. Xuddi shunday.

private async Task CreateRoles(IServiceProvider serviceProvider)
    {
        //initializing custom roles 
        var RoleManager = serviceProvider.GetRequiredService>();
        var UserManager = serviceProvider.GetRequiredService>();
        string[] roleNames = { "Admin", "Manager", "Member" };
        IdentityResult roleResult;

        foreach (var roleName in roleNames)
        {
            var roleExist = await RoleManager.RoleExistsAsync(roleName);
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1
                roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
            }
        }

        //Here you could create a super user who will maintain the web app
        var poweruser = new ApplicationUser
        {

            UserName = Configuration["AppSettings:UserName"],
            Email = Configuration["AppSettings:UserEmail"],
        };
    //Ensure you have these values in your appsettings.json file
        string userPWD = Configuration["AppSettings:UserPassword"];
        var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);

       if(_user == null)
       {
            var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);
            if (createPowerUser.Succeeded)
            {
                //here we tie the new user to the role
                await UserManager.AddToRoleAsync(poweruser, "Admin");

            }
       }
    }

Startup sinfidagi Configure usulidan CreateRoles (serviceProvider) .wait (); usulini chaqirishingiz mumkin. IServiceProvider kodini Configure sinfida parametr sifatida tekshiring.

Foydalanuvchilarga kirishni filterlash uchun boshqaruvchida rolga asoslangan avtorizatsiyadan foydalanish. Savol 2

Buni osongina qilishingiz mumkin.

[Authorize(Roles="Manager")]
public class ManageController : Controller
{
   //....
}

Shuningdek, rolikga asoslangan avtorizatsiyani ham xuddi shunday usulda qo'llashingiz mumkin. Agar xohlasangiz, bir nechta rolni belgilang

[Authorize(Roles="Admin, Manager")]
public IActionResult Index()
{
/*
 .....
 */ 
}

Bu yaxshi ishlayotgan bo'lsa-da, juda yaxshi amaliyot uchun, siyosatga asoslangan rollarni tekshiruvdan foydalanish haqida o'qishni xohlashingiz mumkin. Buni ASP.NET yadro hujjatida topishingiz mumkin bu erda > yoki bu maqolani bu haqda yozgan edim bu yerda

37
qo'shib qo'ydi
Ushbu link bu savolga javob berishi mumkin bo'lsa-da, javobning muhim qismlarini bu yerga qo'shishingiz va havola qilish uchun havolani taqdim qilish yaxshiroqdir. Linkli sahifalar o'zgartirilsa, faqat aloqa uchun javoblar bekor bo'lishi mumkin. - Sharhdan
qo'shib qo'ydi muallif Jean-François Fabre, manba
Endi u yaxshi ko'rinishga kirishmoqda. +1 (hozirda siz hozirda 1 nafarni haqlamaysiz)
qo'shib qo'ydi muallif Jean-François Fabre, manba
Yangi ApplicationUser qismida, EmailConfirmed = rostni kiritish yaxshiroqmi?
qo'shib qo'ydi muallif egmfrs, manba
Men asp.net yadrosi 2.1 dan foydalanmoqdaman va kodning birinchi satrida bu xato yoziladi: "Bir yoki bir necha xatolik yuz berdi. (Microsoft.AspNetCore.Identity.RoleManager`1" [Microsoft.AspNetCore.Identity.RoleManager`1] uchun xizmat yo'q [Microsoft.AspNe & zwnj; tCore.Identity. Identifikatori]] ro'yxatdan o'tgan.) ". Nima uchun bu erda ishlash kerak emas?
qo'shib qo'ydi muallif mahmoud fathy, manba
Rahmat Jan. Kodning asosiy qismlarini javob sifatida kiritdim va tavsiya etilgan havolalarni havola qildim.
qo'shib qo'ydi muallif Temi Lajumoke, manba

Hisob tekshiruvchisida rollarni yaratish va administrator rolini standart foydalanuvchiga ta'sir qiladigan vazifani chaqiradigan bir harakat yaratdim (ehtimol siz ishlab chiqarilgan standart foydalanuvchini olib tashlashingiz kerak):

    private async Task createRolesandUsers()
    {  

        bool x = await _roleManager.RoleExistsAsync("Admin");
        if (!x)
        {

           //first we create Admin rool    
            var role = new IdentityRole();
            role.Name = "Admin";
            await _roleManager.CreateAsync(role);

            //Here we create a Admin super user who will maintain the website                   

            var user = new ApplicationUser();
            user.UserName = "default";
            user.Email = "[email protected]";

            string userPWD = "somepassword";

            IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);

            //Add default User to Role Admin    
            if (chkUser.Succeeded)
            {
                var result1 = await _userManager.AddToRoleAsync(user, "Admin");
            }
        }

       //creating Creating Manager role     
        x = await _roleManager.RoleExistsAsync("Manager");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Manager";
            await _roleManager.CreateAsync(role);

        }

       //creating Creating Employee role     
        x = await _roleManager.RoleExistsAsync("Employee");
        if (!x)
        {
            var role = new IdentityRole();
            role.Name = "Employee";
            await _roleManager.CreateAsync(role);
        }
  }

Foydalanuvchilarning rollarini boshqarish uchun boshqaruvchi yaratganingizdan so'ng.

24
qo'shib qo'ydi
_roleManager nima?
qo'shib qo'ydi muallif JohnOsborne, manba
bu ajoyib, lekin siz rolikda foydalanuvchilarga ushbu rollarni qanday belgilashingiz va kirish vaqtida foydalanuvchilarning rolini aniqlashingiz mumkin? iltimos, bu xususda emasmi?
qo'shib qo'ydi muallif Yirga, manba
Barcha ishtirokchilar ro'yxatini qanday qilib olsam bo'ladi, men roldan voz kechishni va shu bilan bog'liq rollarni qanday qilib o'zgartirishni xohlayman?
qo'shib qo'ydi muallif Bipn Paul, manba
@BipnPaul Buning uchun usermanager-dan foydalanishingiz mumkin: _userManager.GetUsersInRoleAsync ("admin");
qo'shib qo'ydi muallif Stephane Duteriez, manba
Men JS bilan to'liq ish dasturlarini ishga tushirdim, shuning uchun mening testim asp.net bilan qadimga qo'ydim. Lekin yangi foydalanuvchi yaratganingizda yangi foydalanuvchi bilan "addToRoleAsync" deb chaqirishingiz kerak. Foydalanuvchi huquqini boshqarish uchun quyidagi usulni ta'riflaydigan metod yordamida foydalaning: [Authorize ("admin")].
qo'shib qo'ydi muallif Stephane Duteriez, manba

Temining javobi deyarli to'g'ri, biroq asinxron funktsiyani asinxron bo'lmagan funktsiyadan taklif qila olmaysiz. Siz nima qilishingiz kerak bo'lsa, shunday sinxron funktsiyadagi asenkron chaqiruvlarni amalga oshiring:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentity();

       //Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        CreateRoles(serviceProvider);

    }

    private void CreateRoles(IServiceProvider serviceProvider)
    {

        var roleManager = serviceProvider.GetRequiredService>();
        var userManager = serviceProvider.GetRequiredService>();
        Task roleResult;
        string email = "[email protected]";

        //Check that there is an Administrator role and create if not
        Task hasAdminRole = roleManager.RoleExistsAsync("Administrator");
        hasAdminRole.Wait();

        if (!hasAdminRole.Result)
        {
            roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
            roleResult.Wait();
        }

        //Check if the admin user exists and create it if not
        //Add to the Administrator role

        Task testUser = userManager.FindByEmailAsync(email);
        testUser.Wait();

        if (testUser.Result == null)
        {
            ApplicationUser administrator = new ApplicationUser();
            administrator.Email = email;
            administrator.UserName = email;

            Task newUser = userManager.CreateAsync(administrator, "[email protected]!");
            newUser.Wait();

            if (newUser.Result.Succeeded)
            {
                Task newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
                newUserRole.Wait();
            }
        }

    }

The key to this is the use of the Task<> class and forcing the system to wait in a slightly different way in a synchronous way.

10
qo'shib qo'ydi
Sizning javobingiz savol bilan bog'liq deb o'ylamayman.
qo'shib qo'ydi muallif The_Black_Smurf, manba

Buni (DI) dan foydalanaman:

public class IdentitySeed
{
    private readonly ApplicationDbContext _context;
    private readonly UserManager _userManager;
    private readonly RoleManager _rolesManager;
    private readonly ILogger _logger;

    public IdentitySeed(
        ApplicationDbContext context,
        UserManager userManager,
        RoleManager roleManager,
         ILoggerFactory loggerFactory) {
        _context = context;
        _userManager = userManager;
        _rolesManager = roleManager;
        _logger = loggerFactory.CreateLogger();
    }

    public async Task CreateRoles() {
        if (await _context.Roles.AnyAsync()) {// not waste time
            _logger.LogInformation("Exists Roles.");
            return;
        }
        var adminRole = "Admin";
        var roleNames = new String[] { adminRole, "Manager", "Crew", "Guest", "Designer" };

        foreach (var roleName in roleNames) {
            var role = await _rolesManager.RoleExistsAsync(roleName);
            if (!role) {
                var result = await _rolesManager.CreateAsync(new ApplicationRole { Name = roleName });
                //
                _logger.LogInformation("Create {0}: {1}", roleName, result.Succeeded);
            }
        }
       //administrator
        var user = new ApplicationUser {
            UserName = "Administrator",
            Email = "[email protected]",
            EmailConfirmed = true
        };
        var i = await _userManager.FindByEmailAsync(user.Email);
        if (i == null) {
            var adminUser = await _userManager.CreateAsync(user, "Something*");
            if (adminUser.Succeeded) {
                await _userManager.AddToRoleAsync(user, adminRole);
                //
                _logger.LogInformation("Create {0}", user.UserName);
            }
        }
    }
    //! By: Luis Harvey Triana Vega
}
2
qo'shib qo'ydi
IdentityRole ning ApplicationRole insted-i IDID sifatida identifikatorning asosiy kalitini sozlash uchun ( docs.microsoft.com/en-us/aspnet/core/security/authenticatio‌ n/& hellip; )
qo'shib qo'ydi muallif harveyt, manba

Quyidagi kod ISA bilan ishlaydi.

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, 
        IServiceProvider serviceProvider)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseStaticFiles();

        app.UseIdentity();

       //Add external authentication middleware below. To configure them please see https://go.microsoft.com/fwlink/?LinkID=532715

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        CreateRolesAndAdminUser(serviceProvider);
    }

    private static void CreateRolesAndAdminUser(IServiceProvider serviceProvider)
    {
        const string adminRoleName = "Administrator";
        string[] roleNames = { adminRoleName, "Manager", "Member" };

        foreach (string roleName in roleNames)
        {
            CreateRole(serviceProvider, roleName);
        }

       //Get these value from "appsettings.json" file.
        string adminUserEmail = "[email protected]";
        string adminPwd = "[email protected]!";
        AddUserToRole(serviceProvider, adminUserEmail, adminPwd, adminRoleName);
    }

    /// 
/// Create a role if not exists. ///
 
    /// 
Service Provider
    /// 
Role Name
    private static void CreateRole(IServiceProvider serviceProvider, string roleName)
    {
        var roleManager = serviceProvider.GetRequiredService>();

        Task roleExists = roleManager.RoleExistsAsync(roleName);
        roleExists.Wait();

        if (!roleExists.Result)
        {
            Task roleResult = roleManager.CreateAsync(new IdentityRole(roleName));
            roleResult.Wait();
        }
    }

    /// 
/// Add user to a role if the user exists, otherwise, create the user and adds him to the role. ///
 
    /// 
Service Provider
    /// 
User Email
    /// 
User Password. Used to create the user if not exists.
    /// 
Role Name
    private static void AddUserToRole(IServiceProvider serviceProvider, string userEmail, 
        string userPwd, string roleName)
    {
        var userManager = serviceProvider.GetRequiredService>();

        Task checkAppUser = userManager.FindByEmailAsync(userEmail);
        checkAppUser.Wait();

        ApplicationUser appUser = checkAppUser.Result;

        if (checkAppUser.Result == null)
        {
            ApplicationUser newAppUser = new ApplicationUser
            {
                Email = userEmail,
                UserName = userEmail
            };

            Task taskCreateAppUser = userManager.CreateAsync(newAppUser, userPwd);
            taskCreateAppUser.Wait();

            if (taskCreateAppUser.Result.Succeeded)
            {
                appUser = newAppUser;
            }
        }

        Task newUserRole = userManager.AddToRoleAsync(appUser, roleName);
        newUserRole.Wait();
    }
2
qo'shib qo'ydi

Temi Lajumokening javobidan tashqari, kerakli rollarni yaratib, ularni ASP.NET Core 2.1 MVC veb-ilovasida ga aniq foydalanuvchilarga topshirgandan keyin, ilovani ishga tushirgandan so'ng, sizga xato uslubida xatolik yuz berishi mumkin , hisobni ro'yxatdan o'tkazish yoki boshqarish kabi:

InvalidOperationException: Xizmat turi uchun xizmatni yechib bo'lmadi   'Microsoft.AspNetCore.Identity.UI.Services.IEmailSender' vaqtida   faollashtirishga harakat qilmoqda   "WebApplication.Areas.Identity.Pages.Account.Manage.IndexModel".

AddDefaultUI() usulini qo'shib, shunga o'xshash xato ConfigureServices usulida tezda tuzatilishi mumkin:

services.AddIdentity  ()
//services.AddDefaultIdentity  ()
    .AddEntityFrameworkStores  ()
    .AddDefaultUI ()
    .AddDefaultTokenProviders ();

Tekshiring

Http: //blogs.msdn .microsoft.com/webdev/2018/03/02/aspnetcore-2-1-identifikatorlari/

va github bo'yicha mavzu:

Qo'shimcha ma'lumot olish uchun https://github.com/aspnet/Docs/issues/6784 . .

Va muayyan foydalanuvchi rolini belgilash uchun ApplicationUser o'rniga IdentityUser sinf foydalanish mumkin.

1
qo'shib qo'ydi