Common

  public interface ICacheWriter
{
void AddCache(string key, object value, DateTime expDate);
void AddCache(string key, object value);
object GetCache(string key);
T GetCache<T>(string key);
void SetCache(string key, object value, DateTime extDate);
void SetCache(string key, object value);
}

ICacheWriter

 public class CacheHelper
{
public static ICacheWriter CacheWriter { get; set; } static CacheHelper()
{
CacheWriter = new MemcacheWriter();
}
public static void AddCache(string key, object value, DateTime expDate)
{
CacheWriter.AddCache(key, value, expDate);
}
public static void AddCache(string key, object value)
{
CacheWriter.AddCache(key, value);
} public static object GetCache(string key)
{
return CacheWriter.GetCache(key);
} public static void SetCache(string key, object value, DateTime extTime)
{
CacheWriter.SetCache(key, value, extTime);
} public static void SetCache(string key, object value)
{
CacheWriter.SetCache(key, value);
}
}

CacheHelper

  public class MemcacheWriter : ICacheWriter
{
private MemcachedClient memcachedClient;
public MemcacheWriter()
{
string strAppMemcachedServer = System.Configuration.ConfigurationManager.AppSettings["MemcachedServerList"];
string[] servers = strAppMemcachedServer.Split(','); //初始化池
SockIOPool pool = SockIOPool.GetInstance();
pool.SetServers(servers);
pool.InitConnections = ;
pool.MinConnections = ;
pool.MaxConnections = ;
pool.SocketConnectTimeout = ;
pool.SocketTimeout = ;
pool.MaintenanceSleep = ;
pool.Failover = true;
pool.Nagle = false;
pool.Initialize(); MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();
mc.EnableCompression = false; memcachedClient = mc;
} public void AddCache(string key, object value, DateTime expDate)
{
memcachedClient.Add(key, value, expDate);
} public void AddCache(string key, object value)
{
memcachedClient.Add(key, value);
} public object GetCache(string key)
{
return memcachedClient.Get(key);
} public T GetCache<T>(string key)
{
return (T)memcachedClient.Get(key);
}
public void SetCache(string key, object value, DateTime extDate)
{
memcachedClient.Set(key, value, extDate);
} public void SetCache(string key, object value)
{
memcachedClient.Set(key, value);
}
}

MemcacheWriter

   public static class Utils
{
#region GetSHA1(string str) #
public static string GetSHA1(string str)
{
byte[] cleanBytes = Encoding.Default.GetBytes(str);
byte[] hashedBytes = System.Security.Cryptography.SHA1.Create().ComputeHash(cleanBytes);
return BitConverter.ToString(hashedBytes).Replace("-", "").ToLower();
}
#endregion
}

Utils

WebAPIService

    #region 获取授权的TOKEN
/// <summary>
/// 获取授权的TOKEN
/// </summary>
/// <param name="userId">当前用户ID</param>
/// <returns></returns>
[AcceptVerbs("GET")]
public IHttpActionResult GetTokenResult()
{
long timeStamp = DateTime.Now.ConvertTimestamp();
try
{
string token = Guid.NewGuid().ToString("N");
_msg = new Message()
{
retcode = ,
resTime = timeStamp,
toKen = token,
retmsg = "成功"
};
//缓存到memcached 用户的TOKEN 失效时间是一分钟
CacheHelper.SetCache(token, token, DateTime.Now.AddMinutes());
var toek = CacheHelper.GetCache(token);
}
catch
{
_msg = new Message() { retcode = -, resTime = timeStamp, retmsg = "获取TOKEN失败!" };
}
return Json(_msg);
}
#endregion private bool IsValideLogin(UserLoginInfo userLoginInfo, out Message msg)
{
msg = null;
bool result = false;
long timeStamp = DateTime.Now.ConvertTimestamp();
try
{
//采用DES+KEY 对数据加密 //从memcached 获取用户的授权令牌进行匹配,如果匹配上说明身份已经验证过,无需要二次验证损耗性能
var _sign = CacheHelper.GetCache(userLoginInfo.userId.ToString(CultureInfo.InvariantCulture));
if (_sign != null && !string.IsNullOrEmpty(_sign.ToString()))
{
if (!string.IsNullOrEmpty(userLoginInfo.SIGN) &&
userLoginInfo.SIGN.Equals(_sign.ToString(), StringComparison.OrdinalIgnoreCase))
{
result = true;
}
} //1.从memcached 读取用户的token 检查token 是否授权
var _token = CacheHelper.GetCache(userLoginInfo.TOKEN);
if (_token != null && !string.IsNullOrEmpty(_token.ToString()))
{
//模拟读取数据库已配置的key密钥
string key = "cvuUldfieEULqfjdi92k1-lsdf#*ksdf2jd@ld0"; string userId = userLoginInfo.userId.ToString();
string timeStamps = userLoginInfo.timeStamp.ToString(); //3.SHA1加密匹配参数是否正确
string[] temps = { userId, timeStamps, key, _token.ToString() };
Array.Sort(temps);
string sign = Utils.GetSHA1(string.Join("", temps));
if (!string.IsNullOrEmpty(userLoginInfo.SIGN) &&
sign.Equals(userLoginInfo.SIGN, StringComparison.OrdinalIgnoreCase))
{
result = true;
//设置到memcache 设置有效期为1天时间 授权的临时令牌 分发给用户
//这里可以使用DES加密过的串分发给用户 DES+KEY
CacheHelper.SetCache(userLoginInfo.userId.ToString(CultureInfo.InvariantCulture), sign, DateTime.Now.AddDays());
}
else
{
msg = new Message() { resTime = timeStamp, retcode = -, retmsg = "身份验证失败,非法请求!" };
return result = false;
}
}
else
{
msg = new Message() { resTime = timeStamp, retcode = -, retmsg = "非法请求,未授权的TOKEN" };
return result = false;
}
}
catch
{
msg = new Message() { resTime = timeStamp, retcode = , retmsg = "身份验证服务出错!" };
return result = false;
}
return result;
}

ValuesController

WebAPIClient

    RestClient client = new RestClient("http://192.168.64.231:32768");

             UserLoginInfo User = new UserLoginInfo();

             #region Get 方式请求列表
string str = client.Get("api/values");
Message msg = JsonConvert.DeserializeObject<Message>(str); string userId = "";
string timeStamp = msg.resTime.ToString();
string key = "cvuUldfieEULqfjdi92k1-lsdf#*ksdf2jd@ld0";
string[] temps = { userId, timeStamp, key, msg.toKen };
Array.Sort(temps);
string sign = Utils.GetSHA1(string.Join("", temps)); //1.获取授权的TOKEN
User.userId = userId;
User.TOKEN = msg.toKen;
User.SIGN = sign;
User.timeStamp = msg.resTime.ToString(); Console.WriteLine(str);
#endregion #region Post 方式 添加数据 string postUri = "api/values/1"; //string userJson = @"{""Id"":123,""Age"":12,""UserInfo"":""111""}";
string userJson = JsonConvert.SerializeObject(User);
string postResponse = client.Post(userJson, postUri); Console.WriteLine(postResponse);
#endregion Console.ReadKey();

Program

WebAPI接口调用身份验证的更多相关文章

  1. Java后端API调用身份验证的思考

    在如今信息泛滥的数字时代中对产品安全性的要求越来越高了,就比如说今天要讨论的Java后端API调用的安全性,在你提供服务的接口中一定要保证调用方身份的有效性和合法性,不能让非法的用户进行调用,避免数据 ...

  2. 使用ASP.NET Identity 实现WebAPI接口的Oauth身份验证

    使用ASP.NET Identity 实现WebAPI接口的Oauth身份验证   目前WEB 前后端分离的开发模式比较流行,之前做过的几个小项目也都是前后分离的模式,后端使用asp.net weba ...

  3. 基于JWT的web api身份验证及跨域调用实践

    随着多终端的出现,越来越多的站点通过web api restful的形式对外提供服务,很多网站也采用了前后端分离模式进行开发,因而在身份验证的方式上可能与传统的基于cookie的Session Id的 ...

  4. c# WebApi之身份验证:Basic基础认证

    为什么需要身份认证 身份认证是为了提高接口访问的安全性,如果没有身份验证,那么任何匿名用户只要知道服务器的url,就可以随意访问服务器,从而访问或者操作数据库,这会是很恐怖的事. 什么是Basic基础 ...

  5. Nginx集群之基于Redis的WebApi身份验证

    目录 1       大概思路... 1 2       Nginx集群之基于Redis的WebApi身份验证... 1 3       Redis数据库... 2 4       Visualbox ...

  6. ASP.NET没有魔法——ASP.NET Identity 的“多重”身份验证

    ASP.NET Identity除了提供基于Cookie的身份验证外,还提供了一些高级功能,如多次输入错误账户信息后会锁定用户禁止登录.集成第三方验证.账户的二次验证等,并且ASP.NET MVC的默 ...

  7. MVC - 身份验证

    FormsAuthenticationTicket  使用此类来为用户生成一个身份票据 持有该票据则说明该用户是通过了身份验证的用户 可以随时访问某些资源 我们先创建几个类 //用户 public c ...

  8. 从零搭建一个IdentityServer——聊聊Asp.net core中的身份验证与授权

    OpenIDConnect是一个身份验证服务,而Oauth2.0是一个授权框架,在前面几篇文章里通过IdentityServer4实现了基于Oauth2.0的客户端证书(Client_Credenti ...

  9. 教你如何实现微信小程序与.net core应用服务端的无状态身份验证

    随着.net core2的发布,越来越多人使用.net core2开发各种应用服务端,下面我就结合自己最近开发的一款小程序,给大家分享下,怎么使用小程序登录后,小程序与服务端交互的权限控制. .net ...

随机推荐

  1. perl 判断数组相等的三种方法

    1.数组相等,数组成员相同,位置也相同 一般的如果判断@array1 等于 @array2 a.数组长度相同 $#array1=$#array2, 比较数组长度,不能使用length函数,length ...

  2. 数学软件 之 基于MATLAB的DFP算法

    DFP算法是本科数学系中最优化方法的知识,也是无约束最优化方法中非常重要的两个拟Newton算法之一,上一周写了一周的数学软件课程论文,姑且将DFP算法的实现细节贴出来分享给学弟学妹参考吧,由于博客不 ...

  3. 24. javacript高级程序设计-最佳实践

    1. 最佳实践 l 来自其他语言的代码约定可以用于决定何时进行注释,以及如何进行缩进,不过JavaScript需要针对其松散类型的性质创造一些特殊的约定 l javascript应该定义行为,html ...

  4. Divide and conquer:Aggressive Cows(POJ 2456)

    侵略性的牛 题目大意:C头牛最大化他们的最短距离 常规题,二分法即可 #include <iostream> #include <algorithm> #include < ...

  5. poj 2051.Argus 解题报告

    题目链接:http://poj.org/problem?id=2051 题目意思:题目有点难理解,所以结合这幅图来说吧---- 有一个叫Argus的系统,该系统支持一个 Register 命令,输入就 ...

  6. 使用iScroll时,input等不能输入内容的解决方法(share)

    最近做移动平台的应用,使用iscroll使屏幕上下滑动.发现当使用iscroll后,input等不能输入内容了.只要在iscroll.js文件中加入如下代码就ok了. function allowFo ...

  7. 收集android上开源的酷炫的交互动画和视觉效果:Interactive-animation

    查看网址:http://www.open-open.com/lib/view/open1411443332703.html

  8. Android笔记:去除标题栏

    1: 在oncreate方法中添加requestWindowFeature(Window.FEATURE_NO_TITLE); 必须在setContentView()之前执行. 2: 在Android ...

  9. 方法重载的小demo

    方法的重载(overload)要求:1,同一个类中2,方法名必须相同3,方法的参数列表不同(1,参数的个数不同2,参数类型不同,但是参数名相同) 注:方法的重载与方法的返回值类型没有关系 packag ...

  10. poj1988(并查集)

    题目链接:http://poj.org/problem?id=1988 题意:有n个箱子,初始时每个箱子单独为一列: 接下来有p行输入,M, x, y 或者 C, x: 对于M,x,y:表示将x箱子所 ...