83 lines
2.8 KiB
C#
83 lines
2.8 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using System.Text;
|
|
using YLErp.Web.WebAPI.Models;
|
|
|
|
namespace YLErp.Web.WebAPI.Controllers
|
|
{
|
|
[ApiController]
|
|
public class AuthController : ControllerBase
|
|
{
|
|
[HttpPost("m/api/token"), AllowAnonymous]
|
|
public ApiResult Token()
|
|
{
|
|
if (!Request.Headers.TryGetValue("Authorization", out var authHeaders))
|
|
{
|
|
return new ApiResult { code = 1, msg = "HTTP Header属性Authorization参数未设置" };
|
|
}
|
|
|
|
var authHeader = authHeaders.FirstOrDefault() ?? string.Empty;
|
|
|
|
if (!authHeader.StartsWith("Basic "))
|
|
{
|
|
return new ApiResult { code = 1, msg = "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 ApiResult { code = 1, msg = "HTTP Header属性Authorization参数错误" };
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return new ApiResult { code = 1, msg = 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 ApiResult { code = 1, msg = $"用户({userName})不存在" };
|
|
}
|
|
|
|
//验证通过
|
|
if (!sysUser.CheckPassword(password))
|
|
{
|
|
return new ApiResult { code = 1, msg = "验证未通过" };
|
|
}
|
|
|
|
var identity = UserManager.CreateIdentity(sysUser.Id.ToString(), sysUser.Name, AuthHelper.JwtUserToken);
|
|
var jwtToken = AuthHelper.CreateJwtToken(identity);
|
|
|
|
return new ApiTokenResult
|
|
{
|
|
tokenType = "Bearer",
|
|
accessToken = jwtToken,
|
|
expiresIn = AuthHelper.ExpireInSeconds,
|
|
userId = sysUser.Id,
|
|
userName = sysUser.Name,
|
|
userGroup = sysUser.UserGroup
|
|
};
|
|
}
|
|
}
|
|
}
|