Authentication Asp.net mvc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
namespace Sky.Service.WebApi.Filter
{
/// <summary>
/// 基本验证Attribtue,用以Action的权限处理
/// 注意:全局注册时,如果Action重载,必须变更ActionName以区分同名Action 才能使全局身份验证生效。
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class AuthenticationAttribute : ActionFilterAttribute
{
/// <summary>
/// 检查用户是否有该Action执行的操作权限
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
////////////////////////////////////////////////////
///开发过程,临时去掉身份验证 和 权限检查////
base.OnActionExecuting(actionContext);
return;
//////////////////////////////////////////////////
var attr = actionContext.ActionDescriptor.GetCustomAttributes<RequestRequirementAttribute>();
RequestRequirementAttribute ReqRequirement = attr.Where(a => a is RequestRequirementAttribute).FirstOrDefault();
if (ReqRequirement != null && ReqRequirement.Requirement == RequestAuthority.AllowAnonymous) //允许匿名访问
base.OnActionExecuting(actionContext);
else //非匿名访问
{
string Token = TokenManager.GetToken(HttpContext.Current); //Token
string CurrentIP = IPNetworking.GetIP4Address(((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress);
string CurrentUserAgent = ((System.Web.HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserAgent;
if (string.IsNullOrEmpty(Token))
{
RequestResult<string> Result = new RequestResult<string>()
{
Result = false,
ErrorResult = EnumDefine.RequestErrorEnum.NotLogin,
ErrorMessage = "未登录。"
};
actionContext.Response = GetResponse(actionContext, Result);
return;
}
else
{
TokenStatus TStatus = TokenManager.ValidateToken(Token, CurrentIP, CurrentUserAgent);
if (TStatus == TokenStatus.Valid)
{
if (ReqRequirement != null && ReqRequirement.Requirement == RequestAuthority.AuthenticateNotAuthorize)
{
//不进行授权检查
base.OnActionExecuting(actionContext);
}
else
{
///临时不进行权限检查
// base.OnActionExecuting(actionContext);
//登录凭证有效后 验证Action的访问权限
TokenInfo TokenInf = TokenManager.GetTokenInfo(Token);
MED_USERS User = TokenInf.UserInfo;
string PermissionKey = WebApiHelper.GetPermissionKey(actionContext);
//if (User.MDSD_ACTION != null)
//{
// var find = User.MDSD_ACTION.Where(p => p != null && p.ACTION_KEY == PermissionKey);
// if (find != null && find.ToList().Count > 0)
// {
// base.OnActionExecuting(actionContext);
// return;
// }
//}
RequestResult<string> Result = new RequestResult<string>()
{
Result = false,
ErrorResult = EnumDefine.RequestErrorEnum.Unauthorized,
ErrorMessage = "未授权。"
};
actionContext.Response = GetResponse(actionContext, Result);
return;
}
}
else if (TStatus == TokenStatus.Expire)
{
RequestResult<string> Result = new RequestResult<string>()
{
Result = false,
ErrorResult = EnumDefine.RequestErrorEnum.TokenExpire,
ErrorMessage = "Token到期。"
};
actionContext.Response = GetResponse(actionContext, Result);
return;
}
else
{
RequestResult<string> Result = new RequestResult<string>()
{
Result = false,
ErrorResult = EnumDefine.RequestErrorEnum.Invalid,
ErrorMessage = "Token无效。"
};
actionContext.Response = GetResponse(actionContext, Result);
return;
}
}
}
}
/// <summary>
/// 获取返回信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="actionContext"></param>
/// <param name="Result"></param>
/// <returns></returns>
public HttpResponseMessage GetResponse<T>(HttpActionContext actionContext, RequestResult<T> Result)
{
return actionContext.Request.CreateResponse<RequestResult<T>>(HttpStatusCode.OK, Result, actionContext.ControllerContext.Configuration);
}
/// <summary>
/// 执行Action之后
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
base.OnActionExecuted(actionExecutedContext);
}
}
public class RequestRequirementAttribute : System.Attribute
{
/// <summary>
/// 请求要求
/// </summary>
public RequestAuthority Requirement
{
get
{
return __Requirement;
}
}
private RequestAuthority __Requirement;
/// <summary>
/// 请求要求(默认允许匿名访问)
/// </summary>
/// <param name="_Requirement">默认允许匿名访问</param>
public RequestRequirementAttribute(RequestAuthority _Requirement = RequestAuthority.AllowAnonymous)
{
__Requirement = _Requirement;
}
public class TokenManager
{
/// <summary>
/// Token字典
/// </summary>
private static Dictionary<string, TokenInfo> TokenDictionary;
/// <summary>
/// 临时字典
/// </summary>
private static Dictionary<string, TokenInfo> TempTokenDictionary;
/// <summary>
/// Token时效(分钟)
/// </summary>
private static int __TokenValidTimeLimit = -1;
/// <summary>
/// 私有成员变量,用于Lock
/// </summary>
private static object __LockObj = new object();
/// <summary>
/// 添加Token
/// </summary>
/// <param name="Token"></param>
/// <param name="UserInfo"></param>
/// <returns>Token</returns>
public static TokenInfo CreateToken(MED_USERS _UserInfo, string IP, string UserAgent, string LoginStyle)
{
try
{
if (__TokenValidTimeLimit < 0)
{
__TokenValidTimeLimit = 30; //Token时效(分钟)
int.TryParse(ConfigurationManager.AppSettings["TokenValidTime"], out __TokenValidTimeLimit);
}
TokenInfo TokenInfo = new TokenInfo(_UserInfo, IP, UserAgent, __TokenValidTimeLimit, LoginStyle);
string Token = TokenInfo.Token;
lock (__LockObj)
{
if (TempTokenDictionary == null)
{
TempTokenDictionary = new Dictionary<string, TokenInfo>();
TempTokenDictionary.Add(Token, TokenInfo);
}
else
{
//去除用户唯一性维护
//IEnumerable<KeyValuePair<string, TokenInfo>> List = TokenDictionary.Where(p => p.Value != null && p.Value.UserInfo != null && p.Value.UserInfo.USER_ID == _UserInfo.USER_ID);
//if (List != null)
//{
// List<string> Keys = new List<string>();
// foreach (var Pair in List)
// {
// Keys.Add(Pair.Key);
// }
// Keys.ForEach(p => TokenDictionary.Remove(p));
//}
TempTokenDictionary.Add(Token, TokenInfo);
}
}
return TokenInfo;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 获取令牌
/// </summary>
/// <param name="Context"></param>
/// <returns></returns>
public static string GetToken(HttpContext Context)
{
HttpCookie Cookie = Context.Request.Cookies.Get(MedicalSystem.Bev.Core.WebApi.WebApiSetting.TOKENKEY);//ApplicationSetting.TOKENKEY);
return Cookie == null ? null : Cookie.Value; //Token
}
/// <summary>
/// 验证Token有效性
/// </summary>
/// <param name="Token"></param>
/// <returns></returns>
public static TokenStatus ValidateToken(string Token, string CurrentIP, string CurrentUserAgent)
{
///不存在Token或者前后IP不一致 都表示Token无效
lock (__LockObj)
{
if (TokenDictionary == null || !TokenDictionary.ContainsKey(Token) || !TokenDictionary[Token].ValidateIP(CurrentIP, CurrentUserAgent))
return TokenStatus.Invalid;
else
{
if (TokenDictionary[Token].ValidateTokenTime)
return TokenStatus.Expire;
else
{
TokenDictionary[Token].UpdateTokenTime(); //更新最近访问时间
return TokenStatus.Valid;
}
}
}
}
/// <summary>
/// 获取当前令牌信息
/// </summary>
/// <returns></returns>
public static TokenInfo GetTokenInfo()
{
return GetTokenInfo(HttpContext.Current);
}
/// <summary>
/// 获取当前令牌信息
/// </summary>
/// <param name="Context">当前上下文</param>
/// <returns></returns>
public static TokenInfo GetTokenInfo(HttpContext Context)
{
string Token = GetToken(Context);
return string.IsNullOrEmpty(Token) ? null : GetTokenInfo(Token);
}
/// <summary>
/// 获取Token详细信息
/// </summary>
/// <param name="Token"></param>
/// <returns></returns>
public static TokenInfo GetTokenInfo(string Token)
{
lock (__LockObj)
{
if (TokenDictionary != null && TokenDictionary.ContainsKey(Token))
return TokenDictionary[Token];
else
return null;
}
}
/// <summary>
/// 获取临时Token详细信息
/// </summary>
/// <param name="Token"></param>
/// <returns></returns>
public static TokenInfo GetTempTokenInfo(string Token)
{
lock (__LockObj)
{
if (TempTokenDictionary != null && TempTokenDictionary.ContainsKey(Token))
return TempTokenDictionary[Token];
else
return null;
}
}
/// <summary>
/// 移除Token
/// </summary>
/// <param name="Token"></param>
/// <returns></returns>
public static bool RemoveToken(string Token)
{
lock (__LockObj)
{
bool bRes = false;
if (TokenDictionary != null && TokenDictionary.ContainsKey(Token))
{
bRes = TokenDictionary.Remove(Token);
}
else
bRes = true;
return bRes;
}
}
/// <summary>
/// 扫描Token,移除过期Token
/// </summary>
public static void ScanToken()
{
lock (__LockObj)
{
if (TokenDictionary == null || TokenDictionary.Count == 0)
return;
List<string> NeedRemoveTokens = new List<string>();
foreach (KeyValuePair<string, TokenInfo> kv in TokenDictionary)
{
if (kv.Value.ValidateTokenTime) //Token超时
{
NeedRemoveTokens.Add(kv.Key);
}
}
if (NeedRemoveTokens.Count > 0)
{
NeedRemoveTokens.ForEach(p =>
{
if (TokenDictionary.ContainsKey(p))
TokenDictionary.Remove(p);
});
}
}
}
/// <summary>
/// 删除临时Token
/// </summary>
public static bool RemoveTempToken(string Token)
{
lock (__LockObj)
{
bool bRes = false;
if (TempTokenDictionary != null && TempTokenDictionary.ContainsKey(Token))
{
bRes = TempTokenDictionary.Remove(Token);
}
else
bRes = true;
return bRes;
}
}
/// <summary>
/// 添加Token
/// </summary>
/// <param name="Token"></param>
/// <param name="tokeninfo"></param>
public static void AddToken(TokenInfo tokeninfo)
{
if (tokeninfo == null) return;
lock (__LockObj)
{
if (TokenDictionary == null)
TokenDictionary = new Dictionary<string, TokenInfo>();
if (!TokenDictionary.ContainsKey(tokeninfo.Token))
TokenDictionary.Add(tokeninfo.Token, tokeninfo);
if (TempTokenDictionary != null && TempTokenDictionary.ContainsKey(tokeninfo.Token))
TempTokenDictionary.Remove(tokeninfo.Token);
}
}
}
/// <summary>
/// Token状态
/// </summary>
public enum TokenStatus : int
{
/// <summary>
/// 有效
/// </summary>
Valid = 0,
/// <summary>
/// 无效
/// </summary>
Invalid,
/// <summary>
/// 到期
/// </summary>
Expire
}
}
}
posted on 2017-09-06 20:59 lixiaofeng6363 阅读(224) 评论(0) 编辑 收藏 举报