diff --git a/COMCMS.Common/AuthenticationHelper.cs b/COMCMS.Common/AuthenticationHelper.cs
new file mode 100644
index 0000000..bc0718f
--- /dev/null
+++ b/COMCMS.Common/AuthenticationHelper.cs
@@ -0,0 +1,125 @@
+using System;
+using System.Collections.Generic;
+using System.Security.Claims;
+using System.Security.Principal;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Authentication.Cookies;
+using Microsoft.AspNetCore.Http;
+
+namespace COMCMS.Common
+{
+ ///
+ /// 认证助手
+ ///
+ public class AuthenticationHelper
+ {
+ /*
+ 登陆过程
+
+ //信息类型集合,比如姓名、性别、出生日期
+ var claims = new[]
+ {
+ new Claim("UserName",username)
+ };
+
+ //信息类型集合组合成一张证件,比如身份证、驾照、护照
+ var claimsIdentity = new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
+
+ //持有者,拥有以上证件的持有者,同时有身份证、驾照、护照、教师证的一个人
+ var user = new ClaimsPrincipal(claimsIdentity);
+
+ //注册改证件持有者
+ HttpContext.SignInAsync(
+ CookieAuthenticationDefaults.AuthenticationScheme,
+ user,
+ new AuthenticationProperties
+ {
+ IsPersistent = true,//session跨多个请求,否则只在当前请求有效
+ ExpiresUtc = (remember ?? false) ? (DateTimeOffset?)null : DateTimeOffset.Now.AddMilliseconds(60 * 2),//过期时间,null表示不过期
+ }).Wait();
+ */
+
+ private static ClaimsPrincipal _user => _httpContext.User;
+ private static HttpContext _httpContext => MyHttpContext.Current;
+
+ #region 获取Claim
+
+ ///
+ /// 获取一项claim信息
+ ///
+ /// claim名称
+ ///
+ public static string GetClaim(string claimType)
+ {
+ if (_user != null && _user.HasClaim(c => c.Type == claimType))
+ {
+ return _user.FindFirst(claimType).Value;
+ }
+
+ return "";
+ }
+
+ #endregion
+
+ #region 登录
+
+ ///
+ /// 登录
+ ///
+ /// 身份信息项集合
+ /// 过期时间,null为不过期
+ /// 认证方式,默认为cookie方式
+ ///
+ public static async Task SignInAsync(Claim[] claims, DateTimeOffset? expiresUtc,
+ string authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme)
+ {
+ var claimsIdentity = new ClaimsIdentity(claims, authenticationScheme);
+ var user = new ClaimsPrincipal(claimsIdentity);
+
+ var authenticationProperties = new AuthenticationProperties
+ {
+ IsPersistent = true, //session跨多个请求,否则只在当前请求有效
+ ExpiresUtc = expiresUtc, //过期时间,null表示不过期
+ };
+
+ await _httpContext.SignInAsync(authenticationScheme, user, authenticationProperties);
+ }
+
+ ///
+ /// 登录
+ ///
+ /// 身份证持有者
+ /// 过期时间,null为不过期
+ /// 认证方式,默认为cookie方式
+ ///
+ public static async Task SignInAsync(ClaimsPrincipal claimsPrincipal, DateTimeOffset? expiresUtc,
+ string authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme)
+ {
+ var authenticationProperties = new AuthenticationProperties
+ {
+ IsPersistent = true, //session跨多个请求,否则只在当前请求有效
+ ExpiresUtc = expiresUtc, //过期时间,null表示不过期
+ };
+
+ await _httpContext.SignInAsync(authenticationScheme, claimsPrincipal, authenticationProperties);
+ }
+
+ #endregion
+
+ #region 注销
+
+ ///
+ /// 注销
+ ///
+ /// 认证方式
+ ///
+ public static async Task SignOutAsync(string authenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme)
+ {
+ await _httpContext.SignOutAsync(authenticationScheme);
+ }
+
+ #endregion
+ }
+}
diff --git a/COMCMS.Common/COMCMS.Common.csproj b/COMCMS.Common/COMCMS.Common.csproj
index f43dc64..1482d02 100644
--- a/COMCMS.Common/COMCMS.Common.csproj
+++ b/COMCMS.Common/COMCMS.Common.csproj
@@ -11,4 +11,10 @@
+
+
+ C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.authentication.cookies\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Cookies.dll
+
+
+
diff --git a/COMCMS.Core/COMCMS.Core.csproj b/COMCMS.Core/COMCMS.Core.csproj
index b61a5ca..597039c 100644
--- a/COMCMS.Core/COMCMS.Core.csproj
+++ b/COMCMS.Core/COMCMS.Core.csproj
@@ -13,4 +13,10 @@
+
+
+ C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.aspnetcore.authentication.cookies\2.1.1\lib\netstandard2.0\Microsoft.AspNetCore.Authentication.Cookies.dll
+
+
+
diff --git a/COMCMS.Core/Core/管理员.Biz.cs b/COMCMS.Core/Core/管理员.Biz.cs
index 2abe8c3..3cde3b6 100644
--- a/COMCMS.Core/Core/管理员.Biz.cs
+++ b/COMCMS.Core/Core/管理员.Biz.cs
@@ -4,6 +4,8 @@ using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
+using System.Security.Claims;
+using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Web;
@@ -21,11 +23,14 @@ using XCode.Configuration;
using XCode.DataAccessLayer;
using XCode.Membership;
using COMCMS.Common;
+using Microsoft.AspNetCore.Authentication;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Authentication.Cookies;
namespace COMCMS.Core
{
/// 管理员
- public partial class Admin : Entity
+ public partial class Admin : Entity, IIdentity
{
#region 对象操作
static Admin()
@@ -95,6 +100,10 @@ namespace COMCMS.Core
#endregion
#region 扩展属性
+ string IIdentity.Name { get; }
+ string IIdentity.AuthenticationType { get; }
+ bool IIdentity.IsAuthenticated { get; }
+
private AdminRoles _Roles;
/// 用户对应的管理组
public AdminRoles Roles
@@ -175,7 +184,9 @@ namespace COMCMS.Core
{
if (IsAdminLogin())
{
- return Find(_.UserName == SessionHelper.GetSession(sessionAdminNameKey).ToString());
+ //return Find(_.UserName == SessionHelper.GetSession(sessionAdminNameKey).ToString());
+ return Find(_.UserName == AuthenticationHelper.GetClaim(sessionAdminNameKey));
+
}
else
{
@@ -230,7 +241,9 @@ namespace COMCMS.Core
//写入Session 和 Cookies
//SessionHelper.WriteSession("rtadminguid", GUID.ToString());
//CookiesHelper.WriteCookie("rtadminguid", GUID.ToString(), 120);
- SetAdminInfo(entity.UserName, entity.PassWord, entity.Id, 0, "", GUID.ToString(), entity.Salt);
+ //SetAdminInfo(entity.UserName, entity.PassWord, entity.Id, 0, "", GUID.ToString(), entity.Salt);
+ SetAdminInfoAsync(entity.UserName, entity.PassWord, entity.Id, 0, "", GUID.ToString(), entity.Salt).Wait();
+
return true;
}
}
@@ -242,16 +255,22 @@ namespace COMCMS.Core
/// 是否登录
public static bool IsAdminLogin()
{
- string adminName = SessionHelper.GetSession(sessionAdminNameKey).ToString();//用户名
- string adminID = SessionHelper.GetSession(sessionAdminIDKey).ToString();//ID
+ //string adminName = SessionHelper.GetSession(sessionAdminNameKey).ToString();//用户名
+ //string adminID = SessionHelper.GetSession(sessionAdminIDKey).ToString();//ID
+ string adminName = AuthenticationHelper.GetClaim(sessionAdminNameKey);//用户名
+ string adminID = AuthenticationHelper.GetClaim(sessionAdminIDKey);//ID
//如果Session失效,则用Cookies判断
if (string.IsNullOrEmpty(adminName) || string.IsNullOrEmpty(adminID))
{
- string cooAdminName = CookiesHelper.GetCookie(cookiesAdminNameKey);//用户名
- string cooAdminID = CookiesHelper.GetCookie(cookiesAdminIDKey);//ID
- string cooLoginInfo = CookiesHelper.GetCookie(cookiesAdminInfoKey);//信息
- string cooAdminLogID = CookiesHelper.GetCookie(cookiesAdminLogIDKey);//日志GUID
+ //string cooAdminName = CookiesHelper.GetCookie(cookiesAdminNameKey);//用户名
+ //string cooAdminID = CookiesHelper.GetCookie(cookiesAdminIDKey);//ID
+ //string cooLoginInfo = CookiesHelper.GetCookie(cookiesAdminInfoKey);//信息
+ //string cooAdminLogID = CookiesHelper.GetCookie(cookiesAdminLogIDKey);//日志GUID
+ string cooAdminName = AuthenticationHelper.GetClaim(cookiesAdminNameKey);//用户名
+ string cooAdminID = AuthenticationHelper.GetClaim(cookiesAdminIDKey);//ID
+ string cooLoginInfo = AuthenticationHelper.GetClaim(cookiesAdminInfoKey);//信息
+ string cooAdminLogID = AuthenticationHelper.GetClaim(cookiesAdminLogIDKey);//日志GUID
if (string.IsNullOrEmpty(cooAdminID) || string.IsNullOrEmpty(cooAdminName) || string.IsNullOrEmpty(cooLoginInfo) || string.IsNullOrEmpty(cooAdminLogID))
{
@@ -273,17 +292,22 @@ namespace COMCMS.Core
//获取日志ID
if (AdminLog.FindByGUID(cooAdminLogID) == null)
{
- ClearInfo();//清除信息
+ //ClearInfo();//清除信息
+ ClearInfoAsync().Wait();
return false;//日志出错
}
//重新写入Session 和 Cookies
- SetAdminInfo(model.UserName, model.PassWord, model.Id, 0, "", cooAdminLogID, model.Salt);
+ //SetAdminInfo(model.UserName, model.PassWord, model.Id, 0, "", cooAdminLogID, model.Salt);
+
+ SetAdminInfoAsync(model.UserName, model.PassWord, model.Id, 0, "", cooAdminLogID, model.Salt).Wait();
+
return true;
}
else
{
- ClearInfo();//清除信息
+ //ClearInfo();//清除信息
+ ClearInfoAsync().Wait();
return false;//信息错误
}
}
@@ -322,6 +346,36 @@ namespace COMCMS.Core
CookiesHelper.WriteCookie(sessionAdminLogIDKey, adminLogID, 120);
}
+ ///
+ /// 设置管理员信息,写入Session 和Cookies
+ ///
+ /// 是否是超级管理员
+ /// 管理员管理权限
+ /// 后台日志ID
+ public static async Task SetAdminInfoAsync(string adminName, string adminPwd, int adminID, int isSupperAdmin, string adminPower, string adminLogID, string adminSalt)
+ {
+ var expiresUtc = DateTimeOffset.Now.AddMinutes(60 * 2);
+
+ var claimsIdentity = new ClaimsIdentity(new[]
+ {
+ new Claim(sessionAdminIDKey, adminID.ToString()),
+ new Claim(sessionAdminNameKey, adminName),
+ new Claim(sessionAdminPowerKey, adminPower),
+ new Claim(sessionIsSupperAdminKey, isSupperAdmin.ToString()),
+ new Claim(sessionAdminLogIDKey, adminLogID),
+
+ new Claim(cookiesAdminIDKey, adminID.ToString()),
+ new Claim(cookiesAdminNameKey, adminName),
+ //2016-6-01 增加IP加密信息,防止cookies被盗用
+ new Claim(cookiesAdminInfoKey, Utils.MD5(adminName + adminPwd + adminSalt + Utils.GetIP())),
+ });
+
+ var genericPrincipal = new ClaimsPrincipal(claimsIdentity);
+
+ await AuthenticationHelper.SignInAsync(genericPrincipal, expiresUtc);
+ }
+
+
///
/// 管理员退出登录,清除信息
///
@@ -341,6 +395,15 @@ namespace COMCMS.Core
CookiesHelper.ClearCookies(sessionAdminLogIDKey);
}
+ ///
+ /// 管理员退出登录,清除信息
+ ///
+ ///
+ public static async Task ClearInfoAsync()
+ {
+ await AuthenticationHelper.SignOutAsync();
+ }
+
///
/// 写入日志
///
@@ -349,10 +412,12 @@ namespace COMCMS.Core
{
if (IsAdminLogin())
{
- string adminLogId = SessionHelper.GetSession(sessionAdminLogIDKey).ToString();
+ //string adminLogId = SessionHelper.GetSession(sessionAdminLogIDKey).ToString();
+ string adminLogId = AuthenticationHelper.GetClaim(sessionAdminLogIDKey);
if (string.IsNullOrEmpty(adminLogId))
{
- adminLogId = CookiesHelper.GetCookie(cookiesAdminLogIDKey);//日志GUID
+ //adminLogId = CookiesHelper.GetCookie(cookiesAdminLogIDKey);//日志GUID
+ adminLogId = AuthenticationHelper.GetClaim(cookiesAdminLogIDKey);//日志GUID
}
if (!string.IsNullOrEmpty(adminLogId))
{
diff --git a/COMCMS.Web/Areas/AdminCP/Controllers/LoginController.cs b/COMCMS.Web/Areas/AdminCP/Controllers/LoginController.cs
index 91a09e2..ebb20d2 100644
--- a/COMCMS.Web/Areas/AdminCP/Controllers/LoginController.cs
+++ b/COMCMS.Web/Areas/AdminCP/Controllers/LoginController.cs
@@ -115,7 +115,8 @@ namespace COMCMS.Web.Areas.AdminCP.Controllers
///
public IActionResult Logout()
{
- Admin.ClearInfo();
+ //Admin.ClearInfo();
+ Admin.ClearInfoAsync().Wait();
return Redirect("~/AdminCP/Login");
}
#endregion
diff --git a/COMCMS.Web/Startup.cs b/COMCMS.Web/Startup.cs
index e257cee..5501737 100644
--- a/COMCMS.Web/Startup.cs
+++ b/COMCMS.Web/Startup.cs
@@ -23,6 +23,7 @@ using Senparc.CO2NET.RegisterServices;
using Senparc.Weixin;
using Senparc.CO2NET.Cache;
using System.Configuration;
+using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.Extensions.Options;
using Senparc.Weixin.RegisterServices;
@@ -77,6 +78,9 @@ namespace COMCMS.Web
});
services.AddSenparcGlobalServices(Configuration)//Senparc.CO2NET 全局注册
.AddSenparcWeixinServices(Configuration);//Senparc.Weixin 注册(如果使用Senparc.Weixin SDK则添加)
+
+ //注册Cookie认证服务
+ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -108,6 +112,7 @@ namespace COMCMS.Web
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
+ app.UseAuthentication();
app.UseStaticHttpContext();
app.UseMvc(routes =>
diff --git a/COMCMS.Web/appsettings.json b/COMCMS.Web/appsettings.json
index e27ad96..3079065 100644
--- a/COMCMS.Web/appsettings.json
+++ b/COMCMS.Web/appsettings.json
@@ -13,11 +13,11 @@
},
"connectionStrings": {
"dbconn": {
- "connectionString": "Server=.;Port=3306;Database=comcms2;Uid=root;Pwd=root;SslMode=None",
+ "connectionString": "Server=.;Port=3306;Database=comcms2;Uid=root;Pwd=123456;SslMode=None",
"providerName": "MySql.Data.MySqlClient"
},
"mssqlconnon": {
- "connectionString": "server=(local);database=comcmscore;uid=sa;pwd=123456",
+ "connectionString": "server=.\\SQLEXPRESS;database=comcmscore;uid=sa;pwd=123456",
"providerName": "System.Data.SqlClient"
}
}