Skip to content

Commit

Permalink
Merge branch 'master' into publish
Browse files Browse the repository at this point in the history
  • Loading branch information
kklldog committed Aug 17, 2022
2 parents b75cf89 + 2746250 commit e46fa2d
Show file tree
Hide file tree
Showing 14 changed files with 175 additions and 91 deletions.
3 changes: 2 additions & 1 deletion AgileConfig.Server.Apisite/Controllers/AdminController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
using System.Linq.Expressions;
using System.Dynamic;
using AgileConfig.Server.Apisite.Utilites;
using AgileConfig.Server.Service;

namespace AgileConfig.Server.Apisite.Controllers
{
Expand Down Expand Up @@ -49,7 +50,7 @@ public async Task<IActionResult> Login4AntdPro([FromBody] LoginVM model)
{
var user = (await _userService.GetUsersByNameAsync(userName)).First();
var userRoles = await _userService.GetUserRolesAsync(user.Id);
var jwt = JWT.GetToken(user.Id, user.UserName, userRoles.Any(r => r == Role.Admin || r == Role.SuperAdmin));
var jwt = JwtService.GetToken(user.Id, user.UserName, userRoles.Any(r => r == Role.Admin || r == Role.SuperAdmin));
var userFunctions = await _permissionService.GetUserPermission(user.Id);

dynamic param = new ExpandoObject();
Expand Down
10 changes: 6 additions & 4 deletions AgileConfig.Server.Apisite/InitService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Threading.Tasks;
using AgileConfig.Server.Apisite.Utilites;
using AgileConfig.Server.IService;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -37,14 +38,15 @@ public Task StartAsync(CancellationToken cancellationToken)
{
if (Appsettings.IsAdminConsoleMode)
{
_settingService.InitDefaultEnvironment();
_remoteServerNodeProxy.TestEchoAsync();
_serviceHealthCheckService.StartCheckAsync();
_eventRegister.Register();
_settingService.InitDefaultEnvironment();//初始化环境 DEV TEST STAGE PROD
_remoteServerNodeProxy.TestEchoAsync();//开启节点检测
_serviceHealthCheckService.StartCheckAsync();//开启服务健康检测
_eventRegister.Register();//注册 eventbus 的回调
}

if (Appsettings.Cluster)
{
//如果开启集群模式,会自动获取本地的ip注册到节点表,只适合 docker-compose 环境
var ip = GetIp();
if (!string.IsNullOrEmpty(ip))
{
Expand Down
65 changes: 0 additions & 65 deletions AgileConfig.Server.Apisite/JWT.cs

This file was deleted.

6 changes: 3 additions & 3 deletions AgileConfig.Server.Apisite/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ public void ConfigureServices(IServiceCollection services)
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = JwtSetting.Instance.Issuer,
ValidAudience = JwtSetting.Instance.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtSetting.Instance.SecurityKey)),
ValidIssuer = JwtService.Issuer,
ValidAudience = JwtService.Audience,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtService.GetSecurityKey())),
};
});
services.AddCors();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ public async Task Invoke(HttpContext context)
{
await RewriteIndexHtml(filePath);
}

var fileData = await File.ReadAllBytesAsync(filePath); //read file bytes
var lastModified = File.GetLastWriteTime(filePath);
var extType = Path.GetExtension(filePath);
Expand Down
2 changes: 1 addition & 1 deletion AgileConfig.Server.Apisite/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
},

"JwtSetting": {
"SecurityKey": "dfasf343453fsdfa,./,./sdfasf34r3hfhfdb", // ��Կ
"SecurityKey": "", // ��Կ dfasf343453fsdfa,./,./sdfasf34r3hfhfdb
"Issuer": "agileconfig.admin", // �䷢��
"Audience": "agileconfig.admin", // ������
"ExpireSeconds": 86400 // ����ʱ��
Expand Down
2 changes: 1 addition & 1 deletion AgileConfig.Server.Apisite/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
}
},
"JwtSetting": {
"SecurityKey": "dfasf343453fsdfa,./,./sdfasf34r3hfhfdb", // 密钥
"SecurityKey": "", // 密钥 dfasf343453fsdfa,./,./sdfasf34r3hfhfdb
"Issuer": "agileconfig.admin", // 颁发者
"Audience": "agileconfig.admin", // 接收者
"ExpireSeconds": 86400 // 过期时间
Expand Down
12 changes: 12 additions & 0 deletions AgileConfig.Server.IService/ISettingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,17 @@ public interface ISettingService: IDisposable
/// </summary>
/// <returns></returns>
Task<string[]> GetEnvironmentList();

/// <summary>
/// 如果环境变量没有 JwtSetting:SecurityKey 则尝试生成一个key到数据库
/// </summary>
/// <returns></returns>
bool TryInitJwtSecret();

/// <summary>
/// 从配置表获取 jwt secret key
/// </summary>
/// <returns></returns>
string GetJwtTokenSecret();
}
}
76 changes: 76 additions & 0 deletions AgileConfig.Server.Service/JwtService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using AgileConfig.Server.Common;
using AgileConfig.Server.Data.Freesql;
using Microsoft.IdentityModel.Tokens;

namespace AgileConfig.Server.Service;

/// <summary>
/// jwt 相关,因为 jwt 验证配置会在 ConfigureServices 内配置,这个时候 ioc 容器还没配置,不能使用注入,所以直接改成 static class 得了。
/// </summary>
public class JwtService
{
static JwtService()
{
// 如果环境变量没有 JwtSetting:SecurityKey 则尝试生成一个key到数据库
using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance));
settingService.TryInitJwtSecret();
}
public static string Issuer => Global.Config["JwtSetting:Issuer"];
public static string Audience => Global.Config["JwtSetting:Audience"];
public static int ExpireSeconds => int.Parse(Global.Config["JwtSetting:ExpireSeconds"]);

private static string _secretKey;
public static string GetSecurityKey()
{
if (!string.IsNullOrEmpty(_secretKey))
{
return _secretKey;
}

_secretKey = Global.Config["JwtSetting:SecurityKey"];
if (!string.IsNullOrEmpty(_secretKey))
{
return _secretKey;
}

using var settingService = new SettingService(new FreeSqlContext(FreeSQL.Instance));
_secretKey = settingService.GetJwtTokenSecret();

if (string.IsNullOrEmpty(_secretKey))
{
throw new ArgumentNullException($"No JwtSetting SecurityKey");
}

return _secretKey;
}

public static string GetToken(string userId, string userName, bool isAdmin)
{
//创建用户身份标识,可按需要添加更多信息
var claims = new Claim[]
{
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("id", userId, ClaimValueTypes.String), // 用户id
new Claim("username", userName, ClaimValueTypes.String), // 用户名
new Claim("admin", isAdmin.ToString() ,ClaimValueTypes.Boolean) // 是否是管理员
};
var key = Encoding.UTF8.GetBytes(GetSecurityKey());
//创建令牌
var token = new JwtSecurityToken(
issuer: Issuer,
audience: Audience,
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature),
claims: claims,
notBefore: DateTime.Now,
expires: DateTime.Now.AddSeconds(ExpireSeconds)
);

string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

return jwtToken;
}
}
56 changes: 56 additions & 0 deletions AgileConfig.Server.Service/SettingService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Threading.Tasks;
using AgileConfig.Server.Common;
using AgileConfig.Server.Data.Freesql;
using Microsoft.Extensions.Configuration;

namespace AgileConfig.Server.Service
{
Expand All @@ -17,6 +18,7 @@ public class SettingService : ISettingService

public const string DefaultEnvironment = "DEV,TEST,STAGING,PROD";
public const string DefaultEnvironmentKey = "environment";
public const string DefaultJwtSecretKey = "jwtsecret";

public SettingService(FreeSqlContext context)
{
Expand Down Expand Up @@ -147,5 +149,59 @@ public async Task<string[]> GetEnvironmentList()

return env.Value.ToUpper().Split(',');
}

/// <summary>
/// 如果 配置文件或者环境变量没配置 JwtSetting:SecurityKey 则生成一个存库
/// </summary>
/// <returns></returns>
public bool TryInitJwtSecret()
{
var jwtSecretFromConfig = Global.Config["JwtSetting:SecurityKey"];
if (string.IsNullOrEmpty(jwtSecretFromConfig))
{
var jwtSecretSetting = _dbContext.Settings.Where(x => x.Id == DefaultJwtSecretKey).First();
if (jwtSecretSetting == null)
{
_dbContext.Settings.Add(new Setting
{
Id = DefaultJwtSecretKey,
Value = GenreateJwtSecretKey(),
CreateTime = DateTime.Now
});

try
{
var result = _dbContext.SaveChanges();
return result > 0;
}
catch (Exception e)
{
//处理异常,防止多个实例第一次启动的时候,并发生成key值,发生异常,导致服务起不来
Console.WriteLine(e);
}

return false;
}
}
return true;
}

public string GetJwtTokenSecret()
{
var jwtSecretSetting = _dbContext.Settings.Where(x => x.Id == DefaultJwtSecretKey).First();
return jwtSecretSetting?.Value;
}

/// <summary>
/// 生成一个 jwt 加密的 key ,38位
/// </summary>
/// <returns></returns>
private string GenreateJwtSecretKey()
{
var guid1 = Guid.NewGuid().ToString("n");
var guid2 = Guid.NewGuid().ToString("n");

return guid1.Substring(0, 19) + guid2.Substring(0, 19);
}
}
}
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Change log
------------------------------
[1.6.7] - 2022.07.20
* 修复 react ui 不兼容 pathbase 的问题

[1.6.6] - 2022.07.11
* add monaco font content-type

Expand Down
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,16 @@ sudo docker run \
--name agile_config \
-e TZ=Asia/Shanghai \
-e adminConsole=true \
-e db:provider=sqlite \
-e db:conn="Data Source=agile_config.db" \
-e db__provider=sqlite \
-e db__conn="Data Source=agile_config.db" \
-p 5000:5000 \
#-v /your_host_dir:/app/db \
-d kklldog/agile_config:latest
```
通过docker建立一个agile_config实例,其中有3个环境变量需要配置:
1. adminConsole 配置程序是否为管理控制台。如果为true则启用控制台功能,访问该实例会出现管理界面。
2. db:provider 配置程序的数据库类型。目前程序支持:sqlserver,mysql,sqlite, PostgreSql,Oracle 五种数据库。
3. db:conn 配置数据库连接串
2. db__provider 配置程序的数据库类型。目前程序支持:sqlserver,mysql,sqlite, PostgreSql,Oracle 五种数据库。
3. db__conn 配置数据库连接串

> 💥注意:如果通过IIS或者别的方式部署,请自行从主页上的[releases](https://github.com/dotnetcore/AgileConfig/releases)页面下载最新的部署包。如果自己使用源码编译,请先编译react-ui-antd项目把dist内的产物复制到apisite项目的wwwroot/ui目录下。调试的时候需要复制到bin目录下。
Expand All @@ -128,8 +128,8 @@ services:
- TZ=Asia/Shanghai
- adminConsole=true
- cluster=true
- db:provider=mysql
- db:conn= database=configcenter;data source=192.168.0.115;User Id=root;password=mdsd;port=3306
- db__provider=mysql
- db__conn= database=configcenter;data source=192.168.0.115;User Id=root;password=mdsd;port=3306
agile_config_node1:
image: "kklldog/agile_config"
ports:
Expand All @@ -141,8 +141,8 @@ services:
environment:
- TZ=Asia/Shanghai
- cluster=true
- db:provider=mysql
- db:conn= database=configcenter;data source=192.168.0.115;User Id=root;password=mdsd;port=3306
- db__provider=mysql
- db__conn= database=configcenter;data source=192.168.0.115;User Id=root;password=mdsd;port=3306
depends_on:
- agile_config_admin
agile_config_node2:
Expand All @@ -156,8 +156,8 @@ services:
environment:
- TZ=Asia/Shanghai
- cluster=true
- db:provider=mysql
- db:conn= database=configcenter;data source=192.168.0.115;User Id=root;password=mdsd;port=3306
- db__provider=mysql
- db__conn= database=configcenter;data source=192.168.0.115;User Id=root;password=mdsd;port=3306
depends_on:
- agile_config_admin
networks:
Expand Down
4 changes: 2 additions & 2 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ sudo docker run \
--name agile_config \
-e TZ=Asia/Shanghai \
-e adminConsole=true \
-e db:provider=sqlite \
-e db:conn="Data Source=agile_config.db" \
-e db__provider=sqlite \
-e db__conn="Data Source=agile_config.db" \
-p 5000:5000 \
-v /etc/localtime:/etc/localtime \
#-v /your_host_dir:/app/db \
Expand Down
Loading

0 comments on commit e46fa2d

Please sign in to comment.