Files
zszq-trs/Framework/SharedWebApi/ManagerApi/ManagerTokenController.cs
T
2024-05-09 14:06:26 +08:00

110 lines
3.7 KiB
C#

using JWT.Algorithms;
using JWT.Builder;
using JWT.Serializers;
using System.Text;
namespace YLWebAPI.ApiModule.ManagerApi
{
/// <summary>
/// 管理端认证token
/// </summary>
public class ManagerTokenController : ControllerBase
{
[Route("api/token")]
public dynamic ManagerToken(ApiTokenRequest request)
{
if (!Request.Headers.TryGetValue("Authorization", out var authHeaders))
{
return new ApiResponseModel { errcode = 1, errmsg = "HTTP Header属性Authorization参数未设置" };
}
var authHeader = authHeaders.FirstOrDefault() ?? string.Empty;
if (!authHeader.StartsWith("Basic "))
{
return new ApiResponseModel { errcode = 1, errmsg = "HTTP Header属性Authorization参数错误" };
}
int index;
string joinStr;
try
{
var bytes = Convert.FromBase64String(authHeader.Substring(6));
joinStr = Encoding.UTF8.GetString(bytes);
index = joinStr.IndexOf(':');
if (index <= 0)
{
return new ApiResponseModel { errcode = 1, errmsg = "HTTP Header属性Authorization参数错误" };
}
}
catch (Exception ex)
{
return new ApiResponseModel { errcode = 1, errmsg = ex.GetBaseException().Message };
}
var userName = joinStr.Substring(0, index);
var password = joinStr.Substring(index + 1);
using (var db = new ErpBaseContext())
{
var sysUser = db.SystemUsers.Where(o => o.State == (int)UserState.Enabled && (o.LoginName == userName))
.Select(n => new SystemUserDto
{
Id = n.Id,
Name = n.Name,
LoginName = n.LoginName,
Password = n.Password,
UserGroup = n.UserGroup
}).FirstOrDefault();
if (sysUser == null)
{
return new ApiResponseModel { errcode = 1, errmsg = $"用户({userName})不存在" };
}
//验证通过
if (!sysUser.CheckPassword(password))
{
return new ApiResponseModel { errcode = 1, errmsg = "验证未通过" };
}
var expireIn = request?.ExpiresIn ?? 7200;
if (expireIn < 10)
{
expireIn = 10;
}
var token = new JwtBuilder()
.WithAlgorithm(new HMACSHA256Algorithm())
.WithSerializer(new JsonNetSerializer())
.WithSecret(ManagerAuthAttribute.SecretKey)
.AddClaim("exp", DateTimeOffset.UtcNow.AddSeconds(expireIn).ToUnixTimeSeconds())
.AddClaim("userId", sysUser.Id)
.AddClaim("userName", sysUser.Name.TrimToNull() ?? sysUser.LoginName)
.AddClaim("userGroup", sysUser.UserGroup)
.Encode();
return new ApiTokenResponseModel
{
tokenType = "Bearer",
accessToken = token,
expiresIn = expireIn,
userId = sysUser.Id,
userName = sysUser.Name,
userGroup = sysUser.UserGroup
};
}
}
}
public class ApiTokenRequest
{
/// <summary>
/// 有效时间(秒)
/// </summary>
public int? ExpiresIn { get; set; }
}
}