Blazor 5x - قسمت 23 - احراز هویت و اعتبارسنجی کاربران Blazor Server - بخش 3 - کار با نقشهای کاربران
نویسنده: وحید نصیری
تاریخ: ۱۳۹۹/۱۲/۲۹ ۱۰:۴۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
// ...
@*@attribute [Authorize]*@
@code
{
[CascadingParameter] public Task<AuthenticationState> AuthenticationState { get; set; }
protected override async Task OnInitializedAsync()
{
var authenticationState = await AuthenticationState;
if (!authenticationState.User.Identity.IsAuthenticated)
{
var uri = new Uri(NavigationManager.Uri);
NavigationManager.NavigateTo($"/identity/account/login?returnUrl={uri.LocalPath}");
}
// ... namespace BlazorServer.Common
{
public static class ConstantRoles
{
public const string Admin = nameof(Admin);
public const string Customer = nameof(Customer);
public const string Employee = nameof(Employee);
}
} {
"AdminUserSeed": {
"UserName": "vahid@dntips.ir",
"Password": "123@456#Pass",
"Email": "vahid@dntips.ir"
}
} namespace BlazorServer.Models
{
public class AdminUserSeed
{
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
} namespace BlazorServer.App
{
public class Startup
{
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions<AdminUserSeed>().Bind(Configuration.GetSection("AdminUserSeed"));
// ... using System;
using System.Linq;
using System.Threading.Tasks;
using BlazorServer.Common;
using BlazorServer.DataAccess;
using BlazorServer.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
namespace BlazorServer.Services
{
public class IdentityDbInitializer : IIdentityDbInitializer
{
private readonly ApplicationDbContext _dbContext;
private readonly UserManager<IdentityUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IOptions<AdminUserSeed> _adminUserSeedOptions;
public IdentityDbInitializer(
ApplicationDbContext dbContext,
UserManager<IdentityUser> userManager,
RoleManager<IdentityRole> roleManager,
IOptions<AdminUserSeed> adminUserSeedOptions)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
_roleManager = roleManager ?? throw new ArgumentNullException(nameof(roleManager));
_userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
_adminUserSeedOptions = adminUserSeedOptions ?? throw new ArgumentNullException(nameof(adminUserSeedOptions));
}
public async Task SeedDatabaseWithAdminUserAsync()
{
if (_dbContext.Roles.Any(role => role.Name == ConstantRoles.Admin))
{
return;
}
await _roleManager.CreateAsync(new IdentityRole(ConstantRoles.Admin));
await _roleManager.CreateAsync(new IdentityRole(ConstantRoles.Customer));
await _roleManager.CreateAsync(new IdentityRole(ConstantRoles.Employee));
await _userManager.CreateAsync(
new IdentityUser
{
UserName = _adminUserSeedOptions.Value.UserName,
Email = _adminUserSeedOptions.Value.Email,
EmailConfirmed = true
},
_adminUserSeedOptions.Value.Password);
var user = await _dbContext.Users.FirstAsync(u => u.Email == _adminUserSeedOptions.Value.Email);
await _userManager.AddToRoleAsync(user, ConstantRoles.Admin);
}
}
} namespace BlazorServer.App
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IIdentityDbInitializer, IdentityDbInitializer>();
// ... using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Polly;
namespace BlazorServer.DataAccess.Utils
{
public static class MigrationHelpers
{
public static void MigrateDbContext<TContext>(
this IServiceProvider serviceProvider,
Action<IServiceProvider> postMigrationAction
) where TContext : DbContext
{
using var scope = serviceProvider.CreateScope();
var scopedServiceProvider = scope.ServiceProvider;
var logger = scopedServiceProvider.GetRequiredService<ILogger<TContext>>();
using var context = scopedServiceProvider.GetService<TContext>();
logger.LogInformation($"Migrating the DB associated with the context {typeof(TContext).Name}");
var retry = Policy.Handle<Exception>().WaitAndRetry(new[]
{
TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(15)
});
retry.Execute(() =>
{
context.Database.Migrate();
postMigrationAction(scopedServiceProvider);
});
logger.LogInformation($"Migrated the DB associated with the context {typeof(TContext).Name}");
}
}
} public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
host.Services.MigrateDbContext<ApplicationDbContext>(
scopedServiceProvider =>
scopedServiceProvider.GetRequiredService<IIdentityDbInitializer>()
.SeedDatabaseWithAdminUserAsync()
.GetAwaiter()
.GetResult()
);
host.Run();
}
@attribute [Authorize(Roles = ConstantRoles.Admin)]
protected override async Task OnInitializedAsync()
{
var authenticationState = await AuthenticationState;
if (!authenticationState.User.Identity.IsAuthenticated ||
!authenticationState.User.IsInRole(ConstantRoles.Admin))
{
var uri = new Uri(NavigationManager.Uri);
NavigationManager.NavigateTo($"/identity/account/login?returnUrl={uri.LocalPath}");
}