WebApi实现Token验证
为什么要实现Token呢。在我们客户端发送请求时,如果没有校验数据是否合法那么就有可能造成非法请求泄露我们的数据
实现Token的思路
1.客户端通过用户名和密码来获取Token
通过自己的账号和密码登录验证,成功后生成token返回给客户端,并且保存在服务器
2.服务端进行保存Token并且设置有效时间
用什么方法来保存Token呢?
有很多种方法比如在session,数据库中,缓存中。在考察一番后发现还有redis。关于redis的介绍
https://www.runoob.com/redis/redis-install.html
首先先进行安装redis
下载地址:https://github.com/MSOpenTech/redis/releases。
安装完毕之后,打开VS的NuGet》搜索:StackExchange.Redis,安装到项目中
//生成token,我使用用户名加时间戳。此处应该进行一次加密
var token = UserCode+";"+DateTime.Now.ToString();
//保存token
RedisHelper redis = new RedisHelper();
//过期时间设置2分钟,此处应该根据自己的业务需求来进行设置
redis.StringSet(UserCode, token, TimeSpan.FromMinutes(2))
RedisHelper类可以查看其他前辈写的,我这里也是直接使用的代码如下
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace WebApi.Redis
{
public class RedisHelper
{
private int DbNum { get; }
private readonly ConnectionMultiplexer _conn;
public string CustomKey;
#region 构造函数
public RedisHelper(int dbNum = 0)
: this(dbNum, null)
{
}
public RedisHelper(int dbNum, string readWriteHosts)
{
DbNum = dbNum;
_conn =
string.IsNullOrWhiteSpace(readWriteHosts) ?
RedisConnectionHelp.Instance :
RedisConnectionHelp.GetConnectionMultiplexer(readWriteHosts);
}
#endregion
#region 辅助方法
private string AddSysCustomKey(string oldKey)
{
var prefixKey = CustomKey ?? RedisConnectionHelp.SysCustomKey;
return prefixKey + oldKey;
}
private T Do<T>(Func<IDatabase, T> func)
{
var database = _conn.GetDatabase(DbNum);
return func(database);
}
private string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
}
private T ConvertObj<T>(RedisValue value)
{
return JsonConvert.DeserializeObject<T>(value);
}
private List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
}
private RedisKey[] ConvertRedisKeys(List<string> redisKeys)
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
}
#endregion 辅助方法
#region String
#region 同步方法
/// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.StringSet(key, value, expiry));
}
/// <summary>
/// 保存多个key value
/// </summary>
/// <param name="keyValues">键值对</param>
/// <returns></returns>
public bool StringSet(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return Do(db => db.StringSet(newkeyValues.ToArray()));
}
/// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool StringSet<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return Do(db => db.StringSet(key, json, expiry));
}
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public string StringGet(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.StringGet(key));
}
/// <summary>
/// 获取多个Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public RedisValue[] StringGet(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return Do(db => db.StringGet(ConvertRedisKeys(newKeys)));
}
/// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T StringGet<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db => ConvertObj<T>(db.StringGet(key)));
}
/// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public double StringIncrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.StringIncrement(key, val));
}
/// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public double StringDecrement(string key, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.StringDecrement(key, val));
}
#endregion 同步方法
#region 异步方法
/// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await Do(db => db.StringSetAsync(key, value, expiry));
}
/// <summary>
/// 保存多个key value
/// </summary>
/// <param name="keyValues">键值对</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return await Do(db => db.StringSetAsync(newkeyValues.ToArray()));
}
/// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return await Do(db => db.StringSetAsync(key, json, expiry));
}
/// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public async Task<string> StringGetAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringGetAsync(key));
}
/// <summary>
/// 获取多个Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public async Task<RedisValue[]> StringGetAsync(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys)));
}
/// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> StringGetAsync<T>(string key)
{
key = AddSysCustomKey(key);
string result = await Do(db => db.StringGetAsync(key));
return ConvertObj<T>(result);
}
/// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public async Task<double> StringIncrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringIncrementAsync(key, val));
}
/// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public async Task<double> StringDecrementAsync(string key, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringDecrementAsync(key, val));
}
#endregion 异步方法
#endregion String
#region List
#region 同步方法
/// <summary>
/// 移除指定ListId的内部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRemove(key, ConvertJson(value)));
}
/// <summary>
/// 获取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> ListRange<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvetList<T>(values);
});
}
/// <summary>
/// 入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRightPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRightPush(key, ConvertJson(value)));
}
/// <summary>
/// 出队
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListRightPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return ConvertObj<T>(value);
});
}
/// <summary>
/// 入栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListLeftPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListLeftPush(key, ConvertJson(value)));
}
/// <summary>
/// 出栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListLeftPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListLeftPop(key);
return ConvertObj<T>(value);
});
}
/// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long ListLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.ListLength(key));
}
#endregion 同步方法
#region 异步方法
/// <summary>
/// 移除指定ListId的内部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRemoveAsync(key, ConvertJson(value)));
}
/// <summary>
/// 获取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> ListRangeAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.ListRangeAsync(key));
return ConvetList<T>(values);
}
/// <summary>
/// 入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRightPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRightPushAsync(key, ConvertJson(value)));
}
/// <summary>
/// 出队
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListRightPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListRightPopAsync(key));
return ConvertObj<T>(value);
}
/// <summary>
/// 入栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListLeftPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value)));
}
/// <summary>
/// 出栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListLeftPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListLeftPopAsync(key));
return ConvertObj<T>(value);
}
/// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> ListLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.ListLengthAsync(key));
}
#endregion 异步方法
#endregion List
#region Hash
#region 同步方法
/// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashExists(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashExists(key, dataKey));
}
/// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool HashSet<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string json = ConvertJson(t);
return db.HashSet(key, dataKey, json);
});
}
/// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashDelete(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDelete(key, dataKey));
}
/// <summary>
/// 移除hash中的多个值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public long HashDelete(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return Do(db => db.HashDelete(key, dataKeys.ToArray()));
}
/// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public T HashGet<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return ConvertObj<T>(value);
});
}
/// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public double HashIncrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.HashIncrement(key, dataKey, val));
}
/// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public double HashDecrement(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDecrement(key, dataKey, val));
}
/// <summary>
/// 获取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> HashKeys<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
RedisValue[] values = db.HashKeys(key);
return ConvetList<T>(values);
});
}
#endregion 同步方法
#region 异步方法
/// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashExistsAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashExistsAsync(key, dataKey));
}
/// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return await Do(db =>
{
string json = ConvertJson(t);
return db.HashSetAsync(key, dataKey, json);
});
}
/// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashDeleteAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDeleteAsync(key, dataKey));
}
/// <summary>
/// 移除hash中的多个值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray()));
}
/// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<T> HashGeAsync<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = await Do(db => db.HashGetAsync(key, dataKey));
return ConvertObj<T>(value);
}
/// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public async Task<double> HashIncrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashIncrementAsync(key, dataKey, val));
}
/// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public async Task<double> HashDecrementAsync(string key, string dataKey, double val = 1)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDecrementAsync(key, dataKey, val));
}
/// <summary>
/// 获取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> HashKeysAsync<T>(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = await Do(db => db.HashKeysAsync(key));
return ConvetList<T>(values);
}
#endregion 异步方法
#endregion Hash
#region SortedSet 有序集合
#region 同步方法
/// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public bool SortedSetAdd<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetAdd(key, ConvertJson<T>(value), score));
}
/// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public bool SortedSetRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetRemove(key, ConvertJson(value)));
}
/// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> SortedSetRangeByRank<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SortedSetRangeByRank(key);
return ConvetList<T>(values);
});
}
/// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long SortedSetLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetLength(key));
}
#endregion 同步方法
#region 异步方法
/// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public async Task<bool> SortedSetAddAsync<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson<T>(value), score));
}
/// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<bool> SortedSetRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value)));
}
/// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.SortedSetRangeByRankAsync(key));
return ConvetList<T>(values);
}
/// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> SortedSetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetLengthAsync(key));
}
#endregion 异步方法
#endregion SortedSet 有序集合
#region key
/// <summary>
/// 删除单个key
/// </summary>
/// <param name="key">redis key</param>
/// <returns>是否删除成功</returns>
public bool KeyDelete(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyDelete(key));
}
/// <summary>
/// 删除多个key
/// </summary>
/// <param name="keys">rediskey</param>
/// <returns>成功删除的个数</returns>
public long KeyDelete(List<string> keys)
{
List<string> newKeys = keys.Select(AddSysCustomKey).ToList();
return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys)));
}
/// <summary>
/// 判断key是否存储
/// </summary>
/// <param name="key">redis key</param>
/// <returns></returns>
public bool KeyExists(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExists(key));
}
/// <summary>
/// 重新命名key
/// </summary>
/// <param name="key">就的redis key</param>
/// <param name="newKey">新的redis key</param>
/// <returns></returns>
public bool KeyRename(string key, string newKey)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyRename(key, newKey));
}
/// <summary>
/// 设置Key的时间
/// </summary>
/// <param name="key">redis key</param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExpire(key, expiry));
}
#endregion key
#region 发布订阅
/// <summary>
/// Redis发布订阅 订阅
/// </summary>
/// <param name="subChannel"></param>
/// <param name="handler"></param>
public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Subscribe(subChannel, (channel, message) =>
{
if (handler == null)
{
Console.WriteLine(subChannel + " 订阅收到消息:" + message);
}
else
{
handler(channel, message);
}
});
}
/// <summary>
/// Redis发布订阅 发布
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel"></param>
/// <param name="msg"></param>
/// <returns></returns>
public long Publish<T>(string channel, T msg)
{
ISubscriber sub = _conn.GetSubscriber();
return sub.Publish(channel, ConvertJson(msg));
}
/// <summary>
/// Redis发布订阅 取消订阅
/// </summary>
/// <param name="channel"></param>
public void Unsubscribe(string channel)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Unsubscribe(channel);
}
/// <summary>
/// Redis发布订阅 取消全部订阅
/// </summary>
public void UnsubscribeAll()
{
ISubscriber sub = _conn.GetSubscriber();
sub.UnsubscribeAll();
}
#endregion 发布订阅
#region 其他
public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
}
public IDatabase GetDatabase()
{
return _conn.GetDatabase(DbNum);
}
public IServer GetServer(string hostAndPort)
{
return _conn.GetServer(hostAndPort);
}
/// <summary>
/// 设置前缀
/// </summary>
/// <param name="customKey"></param>
public void SetSysCustomKey(string customKey)
{
CustomKey = customKey;
}
#endregion 其他
}
}
redis类代码如下
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace WebApi.Redis
{
/// <summary>
/// ConnectionMultiplexer对象管理帮助类
/// </summary>
public static class RedisConnectionHelp
{
//配置:系统自定义Key前缀
public static readonly string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? "";
//配置:Redis连接字符串:127.0.0.1:6379,allowadmin=true
private static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisExchangeHosts"].ConnectionString;
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>();
/// <summary>
/// 单例获取
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
/// <summary>
/// 缓存获取
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
{
if (!ConnectionCache.ContainsKey(connectionString))
{
ConnectionCache[connectionString] = GetManager(connectionString);
}
return ConnectionCache[connectionString];
}
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
connectionString = connectionString ?? RedisConnectionString;
var connect = ConnectionMultiplexer.Connect(connectionString);
//注册如下事件
connect.ConnectionFailed += MuxerConnectionFailed;
connect.ConnectionRestored += MuxerConnectionRestored;
connect.ErrorMessage += MuxerErrorMessage;
connect.ConfigurationChanged += MuxerConfigurationChanged;
connect.HashSlotMoved += MuxerHashSlotMoved;
connect.InternalError += MuxerInternalError;
return connect;
}
#region 事件
/// <summary>
/// 配置更改时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
{
Console.WriteLine("Configuration changed: " + e.EndPoint);
}
/// <summary>
/// 发生错误时
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
{
Console.WriteLine("ErrorMessage: " + e.Message);
}
/// <summary>
/// 重新建立连接之前的错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("ConnectionRestored: " + e.EndPoint);
}
/// <summary>
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
{
Console.WriteLine("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
}
/// <summary>
/// 更改集群
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
{
Console.WriteLine("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
}
/// <summary>
/// redis类库错误
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
{
Console.WriteLine("InternalError:Message" + e.Exception.Message);
}
#endregion 事件
}
}
3.客户端每次发送请求都带上Token
客户端进行请求时在请求头部添加参数Token然后带上服务器之前返回的Token
4.服务端进行校验Token是否正确以及是否过期,如果过期或者不正确那么就不能返回数据
创建一个过滤器进行全局过滤
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace WebApi.App_Start
{
public class ApiSecurityFilter: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if(actionContext.Request.RequestUri.LocalPath!= "/User/login")
{
//获得请求头
string value = HttpContext.Current.Request.Headers["Token"];
if (!string.IsNullOrEmpty(value))
{
string str = Redis.DesEncrypt.Decrypt(value, "NMMFUSHI");
string UserCode = str.Split(';')[0];
//查询
string Token = new Redis.RedisHelper().StringGet(UserCode);
if (Token != value || string.IsNullOrEmpty(Token))
{
actionContext.Response = ReuDate.GetReuDate(400, "非法请求", null);
}
else
{
Redis.RedisHelper redis = new Redis.RedisHelper();
redis.StringSet(UserCode, Token, TimeSpan.FromMinutes(2));
}
}
else
{
actionContext.Response= ReuDate.GetReuDate(400, "非法请求", null);
}
}
}
}
}
WebApi实现Token验证的更多相关文章
- MVC WebApi 实现Token验证
基于令牌的认证 我们知道WEB网站的身份验证一般通过session或者cookie完成的,登录成功后客户端发送的任何请求都带上cookie,服务端根据客户端发送来的cookie来识别用户. WEB A ...
- ASP.NET WebApi实现Token验证
记录笔记,在博客园中有很多实现Token的方法,这是我看过他们学到的,然后找到适合自己的解决方案,自己无聊总结一下学习经验写下的 WebApi后端接口实现Token验证 Token是在客户端频繁向服务 ...
- WebAPI使用Token进行验证
1.需要用到的包 可以先敲代码 发现没有包在添加 2.在项目根目录下Web层添加“Startup”类 这个是Token的配置 3.在WebAPI层添加WebApiConfig类 也是Tok ...
- WebAPI Token 验证
WebAPI Token 验证 登录端 //HttpContext.Current.Session.Timeout = 10; ////生成Ticket //FormsAuthenticationTi ...
- webapi中使用token验证(JWT验证)
本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...
- Asp.Net WebApi一个简单的Token验证
1.前言: WebAPI主要开放数据给手机APP,Pad,其他需要得知数据的系统,或者软件应用.Web 用户的身份验证,及页面操作权限验证是B/S系统的基础功能.我上次写的<Asp.Net MV ...
- 基于gin框架和jwt-go中间件实现小程序用户登陆和token验证
本文核心内容是利用jwt-go中间件来开发golang webapi用户登陆模块的token下发和验证,小程序登陆功能只是一个切入点,这套逻辑同样适用于其他客户端的登陆处理. 小程序登陆逻辑 小程序的 ...
- ASP.NET WebAPI 双向token实现对接小程序登录逻辑
最近在学习用asp.net webapi搭建小程序的后台服务,因为基于小程序端和后台二者的通信,不像OAuth(开放授权),存在第三方应用.所以这个token是双向的,一个是对用户的,一个是对接口的. ...
- ASP.NET MVC WebApi接口授权验证
对于很任何多开发者来说,不管是使用任何一种框架,或者是使用任何一种语言,都要使用面向接口编程.使用面向接口编程的时候,那么就会有很多的权限验证,用户验证等等. 特别是对于一些系统来说,别人想要对接你的 ...
- webapi之权限验证
webapi之权限验证 一.概念: 二.demo: 1.登录时生成token: FormsAuthenticationTicket token = , account, DateTime.Now, D ...
随机推荐
- 【读书笔记】C#高级编程 第十九章 程序集
(一)程序集的含义 程序集是.NET用于部署和配置单元的术语. .NET应用程序包含一个或多个程序集.通常扩展名是EXE或DLL的.NET可执行程序称为程序集. 程序集是自我描述的安装单元,由一个或多 ...
- byte[]数组转换string类型
byte[] OutData = new byte[2048];//交易返回数据 string pBusiCardInfoStr = Encoding.Default.GetString(OutDat ...
- 我也是一个“翻译家”——关于“robust”
每次看到"鲁棒性",总是不知道是什么意思,一度怀疑自己是不是中国人,是不是说汉语.每次都要查英汉字典,然后一次次看到: robust(adj.精力充沛的; 坚定的; 粗野的,粗鲁的 ...
- haproxy + keeplived
两台主机: 192.168.2.163 192.168.2.165 # yum安装haproxy yum install haproxy # cat /etc/haproxy/haproxy.cfg ...
- Fluentd直接传输日志给MongoDB副本集 (replset)
官方文档地址:https://docs.fluentd.org/output/mongo_replset td-agent版本默认没有包含out_mongo插件,需要安装这个插件才能使用 使用的是td ...
- 不可错过的效能利器「GitHub 热点速览 v.22.39」
如果你是一名前端工程师且维护着多个网站,不妨试试本周榜上有名的 HTML-first 的 Qwik,提升网站访问速度只用一招.除了提升网站加载速度的 Qwik,本周周榜上榜的 Whisper 也是一个 ...
- PAT (Basic Level) Practice 1029 旧键盘 分数 20
旧键盘上坏了几个键,于是在敲一段文字的时候,对应的字符就不会出现.现在给出应该输入的一段文字.以及实际被输入的文字,请你列出肯定坏掉的那些键. 输入格式: 输入在 2 行中分别给出应该输入的文字.以及 ...
- 分布式存储系统之Ceph集群部署
前文我们了解了Ceph的基础架构和相关组件的介绍,回顾请参考https://www.cnblogs.com/qiuhom-1874/p/16720234.html:今天我们来部署一个ceph集群: 部 ...
- emqx启用JWT令牌认证(包含hmac-based和public-key)
emqx连接启用jwt令牌认证 jwt令牌 概述 JWT 即 JSON Web Tokens 是一种开放的,用于在两方之间安全地表示声明的行业标准的方法(RFC 7519). 组成 令牌的形式 xxx ...
- hive之数据导入导出
hive数据导入导出 一.导入数据4种方式 建表语句 create table test( name string, friends array, children map<string, in ...