添加用户角色管理功能并更新JWT生成逻辑

This commit is contained in:
罗澜大帅哥 2025-07-09 13:57:43 +08:00
parent 78bd618cd3
commit 276adfe154
10 changed files with 519 additions and 57 deletions

View File

@ -127,7 +127,8 @@ namespace AGSS.Areas.Identity.Pages.Account
_logger.LogInformation("User logged in.");
var user = await _userManager.FindByEmailAsync(Input.Email);
var token = _jwt.GenerateJwtToken(user);
var roles = await _userManager.GetRolesAsync(user);
var token = _jwt.GenerateJwtToken(user,roles);
var frontendCallback = $"{Request.Query["frontendCallback"]}?token={token}";

View File

@ -128,8 +128,8 @@ namespace AGSS.Areas.Identity.Pages.Account
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var user1 = await _userManager.FindByEmailAsync(Input.Email);
var token = _jwt.GenerateJwtToken(user1);
var roles = await _userManager.GetRolesAsync(user);
var token = _jwt.GenerateJwtToken(user,roles);
var frontendCallback = $"{Request.Query["frontendCallback"]}?token={token}";

View File

@ -0,0 +1,117 @@
using AGSS.Models.Entities;
using AGSS.Models.Template;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace AGSS.Controllers.Admin;
[Authorize(Roles = "Admin")]
[Route("api/v1/Admin/[controller]")]
public class AdminRoleControllers:ControllerBase
{
private readonly RoleManager<RoleModel> _roleManager;
private readonly UserManager<UserModel> _userManager; // Assuming UserModel is the type of user
public AdminRoleControllers(RoleManager<RoleModel> roleManager, UserManager<UserModel> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
[HttpPost]
public async Task<IActionResult> AddRole([FromBody] RoleModel role)
{
if (role == null || string.IsNullOrWhiteSpace(role.Name))
{
return Ok(new ReturnTemplate(400,"创建失败,请提供名字",""));
}
var result = await _roleManager.CreateAsync(role);
if (result.Succeeded)
{
return Ok(new ReturnTemplate(200,"创建成功",role));
}
else
{
return Ok(new ReturnTemplate(StatusCodes.Status500InternalServerError,"创建失败","Failed to create role: " + string.Join(", ", result.Errors.Select(e => e.Description))));
}
}
[HttpPost]
public async Task<IActionResult> EndowRole(string userId, string roleName)
{
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return Ok(new ReturnTemplate(400, "用户不存在", ""));
}
var role = await _roleManager.FindByNameAsync(roleName);
if (role == null)
{
return Ok(new ReturnTemplate(400, "角色不存在", ""));
}
var result = await _userManager.AddToRoleAsync(user, role.Name);
if (result.Succeeded)
{
return Ok(new ReturnTemplate(200, "角色分配成功", user));
}
else
{
return Ok(new ReturnTemplate(StatusCodes.Status500InternalServerError, "角色分配失败", "Failed to endow role: " + string.Join(", ", result.Errors.Select(e => e.Description))));
}
}
/// <summary>
/// 通过角色查询用户,支持分页
/// </summary>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> SearchUserFromRole([FromBody] SearchUserFromRoleRequest request)
{
if (string.IsNullOrWhiteSpace(request.RoleName))
{
return Ok(new ReturnTemplate(400, "角色名称不能为空", null));
}
var role = await _roleManager.FindByNameAsync(request.RoleName);
if (role == null)
{
return Ok(new ReturnTemplate(400, "角色不存在", null));
}
var usersInRole = await _userManager.GetUsersInRoleAsync(role.Name);
var totalUsers = usersInRole.Count;
var pagedUsers = usersInRole
.Skip((request.Page - 1) * request.PageSize)
.Take(request.PageSize)
.ToList();
var response = new SearchUserFromRoleResponse
{
TotalCount = totalUsers,
Users = pagedUsers
};
return Ok(new ReturnTemplate(200, "查询成功", response));
}
public class SearchUserFromRoleRequest
{
public string RoleName { get; set; }
public int Page { get; set; } = 1;
public int PageSize { get; set; } = 10;
}
public class SearchUserFromRoleResponse
{
public int TotalCount { get; set; }
public List<UserModel> Users { get; set; }
}
}

View File

@ -4,11 +4,26 @@ using Microsoft.EntityFrameworkCore;
namespace AGSS.DbSet
{
public class ApplicationDbContext : IdentityDbContext<UserModel>
public class ApplicationDbContext : IdentityDbContext<UserModel,RoleModel,string>
{
public override DbSet<UserModel> Users { get; set; }
public override DbSet<RoleModel> Roles { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// 在这里添加额外的配置,如果需要的话
// 例如:
// modelBuilder.Entity<UserModel>().ToTable("CustomUsers");
// modelBuilder.Entity<RoleModel>().ToTable("CustomRoles");
}
}
}

View File

@ -0,0 +1,300 @@
// <auto-generated />
using System;
using AGSS.DbSet;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
#nullable disable
namespace AGSS.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("20250709054553_userrole")]
partial class userrole
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "9.0.6")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AGSS.Models.Entities.RoleModel", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("AGSS.Models.Entities.UserModel", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<int>("AccessFailedCount")
.HasColumnType("integer");
b.Property<string>("Birthday")
.HasMaxLength(20)
.HasColumnType("character varying(20)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Config")
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<string>("Description")
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("Email")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<bool>("EmailConfirmed")
.HasColumnType("boolean");
b.Property<string>("JobCode")
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<string>("JobName")
.HasMaxLength(10)
.HasColumnType("character varying(10)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("boolean");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("timestamp with time zone");
b.Property<string>("NormalizedEmail")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedUserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("PasswordHash")
.HasColumnType("text");
b.Property<string>("PhoneNumber")
.HasColumnType("text");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("boolean");
b.Property<string>("SecurityStamp")
.HasColumnType("text");
b.Property<string>("Sex")
.HasColumnType("text");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("boolean");
b.Property<string>("UserName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasDatabaseName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasDatabaseName("UserNameIndex");
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer");
NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
b.Property<string>("ClaimType")
.HasColumnType("text");
b.Property<string>("ClaimValue")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("ProviderKey")
.HasColumnType("text");
b.Property<string>("ProviderDisplayName")
.HasColumnType("text");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("text");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("RoleId")
.HasColumnType("text");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("text");
b.Property<string>("LoginProvider")
.HasColumnType("text");
b.Property<string>("Name")
.HasColumnType("text");
b.Property<string>("Value")
.HasColumnType("text");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("AGSS.Models.Entities.RoleModel", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("AGSS.Models.Entities.UserModel", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("AGSS.Models.Entities.UserModel", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("AGSS.Models.Entities.RoleModel", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("AGSS.Models.Entities.UserModel", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("AGSS.Models.Entities.UserModel", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace AGSS.Migrations
{
/// <inheritdoc />
public partial class userrole : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

View File

@ -22,6 +22,32 @@ namespace AGSS.Migrations
NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);
modelBuilder.Entity("AGSS.Models.Entities.RoleModel", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("AGSS.Models.Entities.UserModel", b =>
{
b.Property<string>("Id")
@ -109,32 +135,6 @@ namespace AGSS.Migrations
b.ToTable("AspNetUsers", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("text");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("text");
b.Property<string>("Name")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<string>("NormalizedName")
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasDatabaseName("RoleNameIndex");
b.ToTable("AspNetRoles", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
@ -243,7 +243,7 @@ namespace AGSS.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
b.HasOne("AGSS.Models.Entities.RoleModel", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
@ -270,7 +270,7 @@ namespace AGSS.Migrations
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
b.HasOne("AGSS.Models.Entities.RoleModel", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)

View File

@ -3,7 +3,7 @@ using Microsoft.AspNetCore.Identity;
namespace AGSS.Models.Entities;
public class UserModel:IdentityUser
public class UserModel:IdentityUser<string>
{
public string? Sex { get; set; }
@ -19,3 +19,8 @@ public class UserModel:IdentityUser
public string? Birthday { get; set; }
}
public class RoleModel : IdentityRole<string>
{
}

View File

@ -15,28 +15,30 @@ public class Jwt
_configuration = configuration;
}
public string GenerateJwtToken(UserModel user)
public string BuildToken(IEnumerable<Claim> claims)
{
var claims = new[]
DateTime expires = DateTime.Now.AddDays(int.Parse(_configuration["Jwt:ExpireMinutes"]));
byte[] keyBytes = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]);
var secKey = new SymmetricSecurityKey(keyBytes);
var credentials = new SigningCredentials(secKey,
SecurityAlgorithms.HmacSha256Signature);
var tokenDescriptor = new JwtSecurityToken(expires: expires,
signingCredentials: credentials, claims: claims);
return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
}
public async Task<string> GenerateJwtToken(UserModel user,IList<string> roles)
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddMinutes(
Convert.ToDouble(_configuration["Jwt:ExpireMinutes"]));
var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Audience"],
claims: claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
var claims = new List<Claim>();
claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()));
claims.Add(new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()));
// var roles = await user.GetRolesAsync(user);
foreach (string role in roles)
{
claims.Add(new Claim(ClaimTypes.Role, role));
}
string jwtToken = BuildToken(claims);
return jwtToken;
}
}