Exemple #1
0
        public ActionResult PostProduct()
        {
            var productsUrl = Url.RouteUrl("DefaultApi", new
            {
                httproute  = "",
                controller =
                    "products"
            }, "http");

            using (var client = new HttpClient())
            {
                var token = RSAClass.Encrypt("john");
                client.DefaultRequestHeaders.Add("Authorization-Token", token);
                var product = new Product
                {
                    Id   = 1,
                    Name = "test product"
                };
                var result = client
                             .PostAsync <Product>(productsUrl, product, new JsonMediaTypeFormatter())
                             .Result;
                if (result.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return(Content("Sorry you are not authorized to perform this operation"));
                }

                return(Json(true, JsonRequestBehavior.AllowGet));
            }
        }
        public IHttpActionResult Post(UserLogin userLogin)
        {
            // Get user from database using username
            var user = UserRepository.GetByUsername(userLogin.username);

            if (user == null || !user.Active)
            {
                return(Unauthorized());
            }
            else
            {
                // Check the entered password against stored user password
                var passwordValid = user.Authenticate(userLogin.password);
                if (passwordValid)
                {
                    // Generate and return the encrypted token
                    var clientAuthorisation = new ClientAuthorisation(user.Id, DateTime.Now);
                    var encryptedUser       = RSAClass.Encrypt(Newtonsoft.Json.JsonConvert.SerializeObject(clientAuthorisation));
                    return(Ok(encryptedUser));
                }
                else
                {
                    return(Unauthorized());
                }
            }
        }
  public override void OnActionExecuting(HttpActionContext actionContext)
  {
   string token;
 
   try
   {
    token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
   }
   catch (Exception)
   {
    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
    {
     Content = new StringContent("Missing Authorization-Token")
    };
    return;
   }
 
   try
   {
    //This part is where you verify the incoming token
    AuthorizedUserRepository.GetUsers().First(x => x.Name == RSAClass.Decrypt(token));
    base.OnActionExecuting(actionContext);
   }
   catch (Exception)
   {
    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
    {
     Content = new StringContent("Unauthorized User")
    };
    return;
   }
    }
        public IHttpActionResult UserLogin(UserLoginModel objUserLoginModel)
        {
            try
            {
                User objUser = UserFactory.Instance.GetUserData(objUserLoginModel.UserName);
                if (objUser.Password == objUserLoginModel.Password)
                {
                    var token = RSAClass.Encrypt(Convert.ToString(objUserLoginModel.UserName));

                    objUserLoginModel.Id          = objUser.Id;
                    objUserLoginModel.FirstName   = objUser.FirstName;
                    objUserLoginModel.LastName    = objUser.LastName;
                    objUserLoginModel.LoginStatus = "Login Success";
                    objUserLoginModel.Token       = token;
                    objUserLoginModel.ValidDate   = DateTime.Now.AddDays(1);
                }
                else
                {
                    objUserLoginModel.LoginStatus = "Login Failed!";
                }
            }
            catch (Exception ex)
            {
                _olog.LogException(ex, "UserLogin", "v1Controller");
            }

            return(Ok(objUserLoginModel));
        }
Exemple #5
0
        public void RSAParameters()
        {
            var token     = "abundatrade";
            var encrypted = RSAClass.Encrypt(token);
            var decrypted = RSAClass.Decrypt(encrypted);

            Assert.AreEqual(token, decrypted);
        }
 public static RSAClass createInstance()
 {
     if (RSA == null)
     {
         RSA = new RSAClass();
     }
     return(RSA);
 }
 public ActionResult Delete(int id, string token)
 {
     if (RSAClass.Decrypt(token) == "token")
     {
         employeeDB.deleteEmployee(id);
     }
     return(BadRequest());
 }
 public ActionResult <Employee> Get(int id, string token)
 {
     if (RSAClass.Decrypt(token) == "token")
     {
         return(employeeDB.getEmployeeByID(id));
     }
     return(BadRequest());
 }
 public ActionResult Put([FromBody] Employee emp, string token)
 {
     if (RSAClass.Decrypt(token) == "token")
     {
         employeeDB.updateEmployee(emp);
     }
     return(BadRequest());
 }
 public ActionResult <IEnumerable <Employee> > Get(string token)
 {
     if (RSAClass.Decrypt(token) == "token")
     {
         return(employeeDB.getAllEmployee().ToList());
     }
     return(BadRequest());
 }
        public void VerifyToken()
        {
            var token          = "User1";
            var encryptedToken = RSAClass.Encrypt(token);
            var decryptedToken = RSAClass.Decrypt(encryptedToken);

            Console.WriteLine(encryptedToken);
            Assert.Equal(token, decryptedToken);
        }
Exemple #12
0
        public void RSATest()
        {
            var message = "this is a test";

            RSAClass.GenerateKey();

            byte[] rsaEncrypted = RSAClass.Encrypt(Encoding.UTF8.GetBytes(message));
            byte[] rsaDecrypted = RSAClass.Decrypt(rsaEncrypted);

            Console.WriteLine("Original: " + message + "\n");
            Console.WriteLine("Encrypted: " + BitConverter.ToString(rsaEncrypted) + "\n");
            Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(rsaDecrypted));
        }
        public int socketEntrance(string data, ref System.Net.Sockets.Socket socket)
        {
            try
            {
                data = new RSAClass().Accept_PrivateUnEncode(data); //解密 Weteoes_Client (Weteoes_Client_1_1|ComputerName1|shell1)
                if (data == ConfigClass.socket_Hello)
                {
                    return(0);
                }                                                   //如果为Hello

                /* AppConfig */
                AppConfigClass AppConfig     = new AppConfigClass();
                string         socket_Header = AppConfig.GetConfig(ref data);
                if (socket_Header != ConfigClass.socket_Header)
                {
                    return(-3);
                }                                                              //Header

                /* Function */
                int Function = getFunction(ref data);

                /* Sign_in */
                if (!(new UserClass().Sign_in(ref data)))
                {
                    Function = 3;
                }                                                           //判断身份,获取真实命令(去掉user和pass)

                /* Function Switch */
                switch (Function)
                {
                case 1:
                    new ServerClass().entrance(data, ref socket);
                    return(0);

                case 2:
                    new ClientClass().entrance(data);
                    return(0);

                case 3:
                    new MessageClass().writeLog("MainClass::socketEntrance 捕捉到非法用户访问,身份信息不一致");
                    return(-2);

                default:
                    new MessageClass().writeLog("MainClass::socketEntrance 捕捉到非法访问 Data:" + data);
                    return(-1);
                }
            }
            catch {
                return(-5);
            }
        }
Exemple #14
0
        public void AESTest()
        {
            var message = "this is a test 2";

            RSAClass.GenerateKey();

            byte[] password     = Encoding.UTF8.GetBytes("password");
            byte[] aesEncrypted = AESClass.AES_Encryption(Encoding.UTF8.GetBytes(message), password);
            byte[] aesDecypted  = AESClass.AES_Decrypt(aesEncrypted, password);

            Console.WriteLine("Original: " + message + "\n");
            Console.WriteLine("Encrypted: " + BitConverter.ToString(aesEncrypted) + "\n");
            Console.WriteLine("Decrypted: " + Encoding.UTF8.GetString(aesDecypted));
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="token">Hexadecimal string from client</param>
 /// <returns></returns>
 public IUser GetByAuthorisationToken(string token)
 {
     try
     {
         var tokenByteArray      = SoapHexBinary.Parse(token).Value;
         var decryptedClientUser = RSAClass.Decrypt(tokenByteArray);
         var user = Get(decryptedClientUser.UserId);
         return(user);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
 public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
 {
     try
     {
         var token               = context.ActionContext.Request.Headers.GetValues("Authorisation-Token").First();
         var tokenByteArray      = SoapHexBinary.Parse(token).Value;
         var decryptedClientUser = RSAClass.Decrypt(tokenByteArray);
         return(Task.FromResult(0));
     }
     catch (Exception ex)
     {
         // Log to db
         context.ErrorResult = new AuthenticationFailureResponse("Authentication failure", context.Request);
         return(Task.FromResult(0));
     }
 }
Exemple #17
0
        /// <summary>
        /// Validates a validation token
        /// </summary>
        /// <param name="actionContext">The context to execute</param>
        /// <param name="ip">The ip address to verify against</param>
        private void ValidateToken(HttpActionContext actionContext, string ip)
        {
            string token;

            try
            {
                token = actionContext.Request.Headers.GetValues("Authorization-Token").First();
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(@"{""error"": ""Missing Authorization-Token""}")
                };
                return;
            }

            try
            {
                bool allowed = false;

                using (var context = new DataBaseDataContext())
                {
                    allowed = (from ev in context.KeyRestrictions
                               where ev.ApiKey.key == RSAClass.Decrypt(token) && ev.Allowed == true && (ev.IPAddress == ip || ev.IPAddress == "*")
                               select ev).Count() > 0;
                }

                if (!allowed)
                {
                    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent(@"{""error"": ""Unauthorized IP Address""}")
                    };
                }

                base.OnActionExecuting(actionContext);
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    Content = new StringContent(@"{""error"": ""Unauthorized User""}")
                };
                return;
            }
        }
        protected override Task <HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            try
            {
                if (!request.Headers.Contains("Authorization-Token"))
                {
                    return(Task <HttpResponseMessage> .Factory.StartNew(() =>
                    {
                        return new HttpResponseMessage(HttpStatusCode.BadRequest)
                        {
                            Content = new StringContent("You need to include Authorization-Token")
                        };
                    }));
                }
                var token = request.Headers.GetValues("Authorization-Token").FirstOrDefault();
                if (string.IsNullOrEmpty(token))
                {
                    return(Task <HttpResponseMessage> .Factory.StartNew(() =>
                    {
                        return new HttpResponseMessage(HttpStatusCode.BadRequest)
                        {
                            Content = new StringContent("Missing Authorization-Token")
                        };
                    }));
                }
                var      decryptedToken = RSAClass.Decrypt(token); // TODO: do your query to find the user
                var      user           = decryptedToken;
                var      identity       = new GenericIdentity(decryptedToken);
                string[] roles          = new[] { "Users", "Testers" };
                var      principal      = new GenericPrincipal(identity, roles);
                Thread.CurrentPrincipal = principal;
            }
            catch
            {
                return(Task <HttpResponseMessage> .Factory.StartNew(() =>
                {
                    return new HttpResponseMessage(HttpStatusCode.InternalServerError)
                    {
                        Content = new StringContent("Error encountered in authorization token")
                    };
                }));
            }

            return(base.SendAsync(request, cancellationToken));
        }
Exemple #19
0
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            string token;

            try
            {
                // 首先判断请求是否包含了Token,如果没有包含可返回异常请求信息
                if (actionContext.Request.Headers.Contains(RQUESTHEADERTOKENKEY))
                {
                    token = actionContext.Request.Headers.GetValues(RQUESTHEADERTOKENKEY).First();
                    string authSiteID = actionContext.Request.Headers.GetValues(AUTHSITEID).First();
                    string authSite   = actionContext.Request.Headers.GetValues(AUTHSITE).First();/// TODO:这里还可以对授权站点进行验证
                    // 验证Token是否正确
                    if (RSAClass.Decrypt(token) == (authSite + authSiteID + DateTime.Now.ToString("yyyyMMdd")))
                    {
                        base.OnActionExecuting(actionContext);
                    }
                    else
                    {
                        // 验证失败
                        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                        {
                            Content = new StringContent("Unauthorized Site")
                        };
                        return;
                    }
                }
                else
                {
                    // 验证失败
                    actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                    {
                        Content = new StringContent("Unauthorized Site")
                    };
                    return;
                }
            }
            catch (Exception)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
                {
                    Content = new StringContent("Missing Authorization-Token")
                };
                return;
            }
        }
Exemple #20
0
        public ActionResult GetProducts()
        {
            var productsUrl = Url.RouteUrl("DefaultApi", new
            {
                httproute  = "",
                controller =
                    "products"
            }, "http");

            using (var client = new HttpClient())
            {
                var token = RSAClass.Encrypt("john");
                client.DefaultRequestHeaders.Add("Authorization-Token", token);
                var products = client
                               .GetAsync(productsUrl)
                               .Result
                               .Content
                               .ReadAsAsync <IEnumerable <Product> >()
                               .Result;
                return(Json(products, JsonRequestBehavior.AllowGet));
            }
        }
Exemple #21
0
        public T GetAuth <T>(string url)
        {
            T returnResult;

            using (var client = new HttpClient())
            {
                try
                {
                    client.DefaultRequestHeaders.Add(RQUESTHEADERTOKENKEY, RSAClass.Encrypt(GetToken()));
                    client.DefaultRequestHeaders.Add(AUTHSITEID, ConfigurationManager.AppSettings["SiteID"]);
                    client.DefaultRequestHeaders.Add(AUTHSITE, ConfigurationManager.AppSettings["SiteDomain"]);
                    HttpResponseMessage response = null;
                    client.GetAsync(url).ContinueWith(
                        (requestTask) =>
                    {
                        response = requestTask.Result;
                    }).Wait(60000);
                    if (response.IsSuccessStatusCode)
                    {
                        returnResult = response.Content.ReadAsAsync <T>().Result;
                    }
                    else
                    {
                        throw new Exception(response.ReasonPhrase);
                        //returnResult = default(T);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    client.Dispose();
                }
            }
            return(returnResult);
        }