前言
开发环境:Asp.netCore 版本为3.1
1.创建Web项目,并添加项目引用
创建web项目
dotnet new web
编辑项目文件,填加nuget包引用
<ItemGroup>
<PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.0.4" />
<PackageReference Include="IdentityServer4.EntityFramework" Version="4.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.1.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="3.1.0" />
</ItemGroup>
2.创建一个json文件,用于配置Client,Api资源
id4.json 配置如下
{
//客户端
"Clients": [
{
"ClientId": "wpf",
"ClientSecrets": [
{
"Value": "wpf_secret" }
],
"AllowedGrantTypes": [ "client_credentials" ],
"Enabled": "true",
"AllowedScopes": [ "system", "mes" ]
},
{
"ClientId": "web",
"ClientSecrets": [
{
"Value": "web_secret" }
],
"AllowedGrantTypes": [ "password" ],
"Enabled": "true",
"AllowedScopes": [ "openid", "profile", "system", "mes" ]
}
],
//api接口配置
"ApiScopes": [
{
"Name": "system",
"DisplayName": "系统管理服务",
"Enabled": true
},
{
"Name": "mes",
"DisplayName": "mes系统服务",
"Enabled": true
}
]
}
3.创建ApplicationDbContext 继承自 IdentityDbContext 并创建用户,角色等实体类,重写IdentityUser,IdentityRole
代码如下
public class ApplicationDbContext : IdentityDbContext<SysUser, SysRole, string, SysUserClaim, SysUserRole, SysUserLogin, SysRoleClaim, SysUserToken>
{
/// <summary>
/// 组织机构
/// </summary>
public DbSet<SysOrgUnit> OrgUnit {
get; set; }
/// <summary>
/// 系统菜单
/// </summary>
public DbSet<SysMenuMaster> MenuMaster {
get; set; }
/// <summary>
/// 系统菜单(定制化)
/// </summary>
public DbSet<SysMenu> Menu {
get; set; }
/// <summary>
/// 部门
/// </summary>
public DbSet<SysDepartment> Department {
get; set; }
/// <summary>
/// 部门路径
/// </summary>
public string Path {
get; set; }
/// <summary>
/// 层级
/// </summary>
public int Level {
get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<SysUser>().ToTable("SysUser");
builder.Entity<SysUserClaim>().ToTable("SysUserClaim");
builder.Entity<SysUserLogin>().ToTable("SysUserLogin");
builder.Entity<SysUserToken>().ToTable("SysUserToken");
builder.Entity<SysUserRole>().ToTable(<