【新增】后端用户登录增加简单单点登录限制功能。

This commit is contained in:
jianweie code
2024-07-30 00:50:24 +08:00
parent b0439968a9
commit ac4bcb2b7a
5 changed files with 52 additions and 0 deletions

View File

@@ -16,7 +16,9 @@ using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using CoreCms.Net.Auth.Policys;
using CoreCms.Net.Caching.Manual;
using CoreCms.Net.Configuration;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.Utility.Extensions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
@@ -25,6 +27,7 @@ using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using NETCore.Encrypt;
using Newtonsoft.Json;
namespace CoreCms.Net.Auth
{
@@ -109,6 +112,39 @@ namespace CoreCms.Net.Auth
if (!string.IsNullOrEmpty(token.Trim()))
{
context.Token = EncryptProvider.AESDecrypt(token, AppSettingsConstVars.JwtConfigSecretKey);
//简单单点登录校验
if (!string.IsNullOrEmpty(context.Token) && AppSettingsConstVars.UserSSO)
{
var jwtToken = (new JwtSecurityTokenHandler()).ReadJwtToken(context.Token);
var claimsIdentity = new ClaimsIdentity(jwtToken.Claims);
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
var userid = claimsPrincipal?.Claims.FirstOrDefault(c => c.Type == JwtRegisteredClaimNames.Jti)?.Value; //登录时存入claims的用户唯一标识
var mJwt = ManualDataCache.Instance.Get<string>("LoginUser:" + userid);
if (string.IsNullOrEmpty(mJwt))
{
context.Response.Headers.Append("Token-Error-Token", "UserLoginStatusError");
var jm = new AdminUiCallBack();
jm.code = 401;
jm.data = 401;
jm.msg = "Sorry, your login information could not be found.";
context.Response.WriteAsync(JsonConvert.SerializeObject(jm));
return Task.CompletedTask;
}
else
{
if (mJwt != token)
{
context.Response.Headers.Append("Token-Error-Token", "The current user logged in elsewhere");
var jm = new AdminUiCallBack();
jm.code = 401;
jm.data = 401;
jm.msg = "Sorry, your account has already been logged in elsewhere.";
context.Response.WriteAsync(JsonConvert.SerializeObject(jm));
return Task.CompletedTask;
}
}
}
}
else
{

View File

@@ -11,6 +11,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\CoreCms.Net.Caching\CoreCms.Net.Caching.csproj" />
<ProjectReference Include="..\CoreCms.Net.Configuration\CoreCms.Net.Configuration.csproj" />
<ProjectReference Include="..\CoreCms.Net.IRepository\CoreCms.Net.IRepository.csproj" />
<ProjectReference Include="..\CoreCms.Net.IServices\CoreCms.Net.IServices.csproj" />