- static readonlyListstring,string>> ActiveApiKeys =newListstring,string>>();
- private static readonlyListstring,string>> User =newListstring,string>>();
- static UserDatabase()
- {
- User.Add(newTuple<string,string>("Lexan","password"));
- User.Add(newTuple<string,string>("User","password"));
- }
- public staticClaimsPrincipal GetUserFromApiKey(string apiKey)
- {
- varactiveKey = ActiveApiKeys.FirstOrDefault(x=>x.Item2==apiKey);
- if(activeKey==null)
- {
- return null;
- }
- varuserRecord = User.First(x=>x.Item1==activeKey.Item1);
- return newClaimsPrincipal(newGenericIdentity(userRecord.Item1,"Lexan"));
- }
- public static stringValidateUser(stringusername,string password)
- {
- //尝试从 "数据库" 中获取与给定用户名和密码匹配的用户
- varuserRecord = User.FirstOrDefault(x=>x.Item1==username&&x.Item2==password);
- if(userRecord==null)
- {
- return null;
- }
- //既然用户已被验证, 请创建一个可用于后续请求的 api 密钥。
- varapiKey = Guid.NewGuid().ToString();
- ActiveApiKeys.Add(newTuple<string,string>(username,apiKey));
- return apiKey;
- }
- public static voidRemoveApiKey(string apiKey)
- {
- varapiKeyToRemove = ActiveApiKeys.First(x=>x.Item2==apiKey);
- ActiveApiKeys.Remove(apiKeyToRemove);
- }
- public staticTuple<string,string> CreateUser(stringusername,string password)
- {
- varuser =newTuple<string,string>(username,password);
- User.Add(user);
- return user;
- }
来源: http://www.cnblogs.com/R00R/p/6851063.html