ldj/WcfServiceAuthentication/AuthenticationInspector.cs

190 lines
7.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;
using System.Runtime.Serialization;
using DeiNiu.Utils;
using DeiNiu.wms.Data.Model;
using System.Net;
namespace WcfServiceAuthentication
{
public class AuthenticationInspector : IDispatchMessageInspector
{
// protected static log4net.ILog log = log4net.LogManager.GetLogger("logCommon");
public static int testUserId = 0;
public static Dictionary<int, string> authCach = new Dictionary<int, string>();
public static Dictionary<int, int> tmpCodes = new Dictionary<int, int>();
public static List<int> restrictUsers = new List<int>();
static string[] publicServices = { "/Login.svc", "/PortalService.svc", "/MobileService.svc", "/ScheduledService.svc", "/android.svc/login" };
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
//注意引用 System.Runtime.Serialization
string userIdKey = "UserId";
string tokenKey = "Token";
string tmpTokenKey = "tmpToken";
int tmpToken = 0;
int userId =0;
// string Password = request.Headers.GetHeader<string>("Password", "www.test.com");
string token = "";
string requestPath = channel.LocalAddress.Uri.AbsolutePath;
WebHeaderCollection headerCollection = System.ServiceModel.Web.WebOperationContext.Current.IncomingRequest.Headers;
foreach (string item in headerCollection)
{
if (item == userIdKey)
userId = Convert.ToInt32(headerCollection.Get(item));
if (item == tokenKey)
token = headerCollection.Get(item) ;
if (item == tmpTokenKey)
{
tmpToken = Convert.ToInt32(headerCollection.Get(item));
tmpCodes[userId] = tmpToken;
}
}
if (publicServices.Contains(requestPath))
{
return null;
}
string methdPath = request.Properties.Via.AbsolutePath;
if (publicServices.Contains(methdPath))
{
return null;
}
if (userId == 0) //for win client
{
try {
userId = request.Headers.GetHeader<int>("UserId", "www.deinu.com");
// string Password = request.Headers.GetHeader<string>("Password", "www.test.com");
token = request.Headers.GetHeader<string>("Token", "www.deinu.com");
}
catch(System.ServiceModel.MessageHeaderException er)
{
}
}
// LogHelper.debug("svr AuthenticationInspector", string.Format("request: {2},set UserId : {0},set token: {1}, tmpToken: {3}", userId, token, request.ToString(), tmpToken));
// log.Debug( string.Format("svr AuthenticationInspector request: {2},set UserId : {0},set token: {1}, tmpToken: {3}", userId, token, request.ToString(),tmpToken));
if (!validUser(userId, token)) // not in cache
{
LogHelper.debug("svr AuthenticationInspector auth error", string.Format("request: {2}, UserId : {0}, token: {1}", userId, token, request.ToString()));
throw new DeiNiuTimeOutException(WmsConstants.WCF_UN_AUTH_MESSAGE);
}
if (tmpToken > 0)
{
tmpCodes[userId] = tmpToken;
}
return null;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
string res = reply.ToString();
return;
}
public static bool validUser(int userId, string token)
{
if (WmsConstants.IS_ONLINE_RESTRICT && restrictUsers.Count>=WmsConstants.MAX_ONLINE_USERS && !restrictUsers.Contains(userId))
{
LogHelper.debug("AuthenticationInspector", string.Format(" userId {0} is not in the allowed list, current list size {1}, maxSize {2} ", userId, restrictUsers.Count, WmsConstants.MAX_ONLINE_USERS));
return false;
}
//
if (!authCach.ContainsKey(userId)) //检查内存
{
LogHelper.debug("AuthenticationInspector",
string.Format("userId {0} NOT in the cache, to check db...", userId) );
//检查db
Employee em = new Employee();
try
{
if (em.login(token) && em.ID == userId)
{
LogHelper.debug("AuthenticationInspector", string.Format("valid token {0} in the db and token match ", token));
authCach[userId] = token;
}
else
{
LogHelper.debug("AuthenticationInspector",
string.Format("userId {0} and token NOT match db...return false ", userId));
return false;
}
}
catch
{
LogHelper.debug("AuthenticationInspector",
string.Format(" exception happened ...return false ", userId));
return false;
}
}
if(authCach[userId] == token)
{
if (WmsConstants.IS_ONLINE_RESTRICT)
{
checkRestrictUsers(userId);
}
return true;
}
return false;
}
public static void checkRestrictUsers(int userId)
{
if (userId <= 0)
{
return;
}
// LogHelper.debug("1 checkRestrictUsers", string.Format(" checking ..userId {0} , current list size {1}, maxSize {2} ", userId, restrictUsers.Count, WmsConstants.MAX_ONLINE_USERS));
if (!AuthenticationInspector.restrictUsers.Contains(userId))
{
if (AuthenticationInspector.restrictUsers.Count >= WmsConstants.MAX_ONLINE_USERS)
{
LogHelper.debug("checkRestrictUsers", string.Format(" to remove ..userId {0} ", AuthenticationInspector.restrictUsers[0]));
AuthenticationInspector.restrictUsers.RemoveAt(0);
}
AuthenticationInspector.restrictUsers.Add(userId);
foreach (int i in AuthenticationInspector.restrictUsers)
{
LogHelper.debug("checkRestrictUsers", string.Format(" active userId {0} ", i));
}
}
/*
LogHelper.debug("2 checkRestrictUsers", string.Format(" checking ..userId {0} , current list size {1}, maxSize {2} ", userId, restrictUsers.Count, WmsConstants.MAX_ONLINE_USERS));
foreach(int i in AuthenticationInspector.restrictUsers)
{
LogHelper.debug("checkRestrictUsers", string.Format(" active userId {0} ", i));
}
*/
}
}
}