I'm trying to use identity framework and identity framework ui for my application, and i configured identity for roles user and admin but i can just login with roles user. when i login with account role admin then button login is not active, maybe is it. but when i login with account role user or register new account then i can login and go to home page my application This is my code.
program.cs
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Client.Data;
using Client.Areas.Identity.Data;
using Data;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("AuthDbContextConnection") ?? throw new InvalidOperationException("Connection string 'AuthDbContextConnection' not found.");
builder.Services.AddDbContext<AuthDbContext>(options => options.UseSqlServer(connectionString));
builder.Services
.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AuthDbContext>();
// Add services to the container.
var connectString1 = builder.Configuration.GetConnectionString("EntitiesDbContextConnection") ?? throw new InvalidOperationException("Connection string 'EntitiesDbContextConnection' not found.");
builder.Services.AddDbContext<EntitiesDbContext>(options => options.UseSqlServer(connectString1));
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var roles = new[] { "Admin", "User" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}
}
using (var scope = app.Services.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string email = "[email protected]";
string password = "Admin@123";
if (await userManager.FindByEmailAsync(email) == null)
{
var user = new ApplicationUser();
user.Email = email;
user.UserName = email;
await userManager.CreateAsync (user,password);
await userManager.AddToRoleAsync(user, "Admin");
}
}
app.Run();
Login.cshtml
@page
@model LoginModel
@{
ViewData["Title"] = "Log in";
}
@* <h1>@ViewData["Title"]</h1> *@
@* <div class="row">
<div class="col-md-4">
<section>
<form id="account" method="post">
<h2>Use a local account to log in.</h2>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div>
<div class="form-floating mb-3">
<input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true" placeholder="[email protected]" />
<label asp-for="Input.Email" class="form-label">Email</label>
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="form-floating mb-3">
<input asp-for="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" placeholder="password" />
<label asp-for="Input.Password" class="form-label">Password</label>
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="checkbox mb-3">
<label asp-for="Input.RememberMe" class="form-label">
<input class="form-check-input" asp-for="Input.RememberMe" />
@Html.DisplayNameFor(m => m.Input.RememberMe)
</label>
</div>
<div>
<button id="login-submit" type="submit" class="w-100 btn btn-lg btn-primary">Log in</button>
</div>
<div>
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
<p>
<a id="resend-confirmation" asp-page="./ResendEmailConfirmation">Resend email confirmation</a>
</p>
</div>
</form>
</section>
</div>
<div class="col-md-6 col-md-offset-2">
<section>
<h3>Use another service to log in.</h3>
<hr />
@{
if ((Model.ExternalLogins?.Count ?? 0) == 0)
{
<div>
<p>
There are no external authentication services configured. See this <a href="https://go.microsoft.com/fwlink/?LinkID=532715">article
about setting up this ASP.NET application to support logging in via external services</a>.
</p>
</div>
}
else
{
<form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
<div>
<p>
@foreach (var provider in Model.ExternalLogins!)
{
<button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
}
</p>
</div>
</form>
}
}
</section>
</div>
</div> *@
<div class="container-fluid vh-100 overflow-auto">
<div class="row vh-100">
<div class="col-lg-6 bg-gray p-5 text-center">
<h4 class="text-center fw-bolder fs-2">Register</h4>
<p class="mb-3 fs-7">Register Now and Fell the New Digital World</p>
<a href="/Identity/Account/Register">
<button class="btn fw-bold mb-5 btn-outline-success px-4 rounded-pill">
Sign Up
</button>
</a>
<div class="img-cover p-4">
<img src="~/Content2/assets/images/loginbg.svg" alt="" />
</div>
</div>
<div class="col-lg-6 p vh-100">
<div class="row d-flex vh-100">
<div class="col-md-8 p-4 ikigui m-auto text-center align-items-center">
<h4 class="text-center fw-bolder mb-4 fs-2">Login</h4>
<section>
<form id="account" method="post">
<div class="input-group mb-4">
<input asp-for="Input.Email" class="form-control" autocomplete="username" aria-required="true"
placeholder="[email protected]" />
<label asp-for="Input.Email" class="form-label">Email</label>
<span asp-validation-for="Input.Email" class="text-danger"></span>
</div>
<div class="input-group mb-4">
<input asp-for="Input.Password" class="form-control" autocomplete="current-password"
aria-required="true" placeholder="password" />
<label asp-for="Input.Password" class="form-label">Password</label>
<span asp-validation-for="Input.Password" class="text-danger"></span>
</div>
<div class="checkbox mb-3">
<label asp-for="Input.RememberMe" class="form-label">
<input class="form-check-input" asp-for="Input.RememberMe" />
@Html.DisplayNameFor(m => m.Input.RememberMe)
</label>
</div>
<div>
<button id="login-submit" type="submit" class="w-100 btn btn-lg btn-primary">
Log in
</button>
</div>
<div>
<p>
<a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>
</p>
<p>
<a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
</p>
<p>
<a id="resend-confirmation" asp-page="./ResendEmailConfirmation">Resend email confirmation</a>
</p>
</div>
</form>
</section>
<p class="text-center py-4 fw-bold fs-8">
Or Sign in with social platforms
</p>
<ul class="d-inline-block mx-auto">
<li class="float-start px-3">
<a href=""><i class="bi bi-facebook"></i></a>
</li>
<li class="float-start px-3">
<a href=""><i class="bi bi-twitter"></i></a>
</li>
<li class="float-start px-3">
<a href=""><i class="bi bi-linkedin"></i></a>
</li>
<li class="float-start px-3">
<a href=""><i class="bi bi-google"></i></a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
@section Scripts {
<partial name="_ValidationScriptsPartial" />
}
Index.cshtml
@using Client.Areas.Identity.Data
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignUser
@inject UserManager<ApplicationUser> UserManager
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_LayoutPage.cshtml";
}
@if (User.IsInRole("Admin"))
{
<h1>this is view for admin</h1>
}
else
{
<h1>this is view of user</h1>
}
HomeController.cs
using Client.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace Client.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
I tried to create an application with more than one role. specifically, I'm expecting to have 2 roles. I tried to work with identity framework, and it was not as expected.
Everyone also see it on Github in branch "demo-working-with-idenity": https://github.com/toiQS/Noname/tree/demo-working-with-identity