Esempio n. 1
0
        public bool IsAuthorized(string username, string password)
        {
            string uName = string.Empty;
            string uPass = string.Empty;
            string uSt   = string.Empty;
            int    uID;

            if (!string.IsNullOrEmpty(username))
            {
                username = username.ToLower();
            }
            var          lastaccess  = DateTime.UtcNow;
            const string strSQLQuery = @"
SELECT id, username, password, status
FROM swagger
WHERE lower(username) = @username;
UPDATE swagger SET lastaccess = @lastaccess, lastipaddr = @ipaddr WHERE lower(username) = @username;";

            try
            {
                using (var connection = new System.Data.SQLite.SQLiteConnection(VarsSubsFunc.mStrSQLiteConnString))
                {
                    using (var command = new System.Data.SQLite.SQLiteCommand(strSQLQuery, connection))
                    {
                        command.CommandType = CommandType.Text;
                        command.Parameters.Add(new System.Data.SQLite.SQLiteParameter("@username", username));
                        command.Parameters.Add("@lastaccess", DbType.DateTime);
                        command.Parameters["@lastaccess"].Value = lastaccess;
                        command.Parameters.Add("@ipaddr", DbType.String);
                        command.Parameters["@ipaddr"].Value = VarsSubsFunc.GetIpAddress().Trim();
                        connection.Open();
                        using (var reader = command.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                while (reader.Read())
                                {
                                    uID   = Conversions.ToInteger(reader[0]);
                                    uName = reader[1].ToString();
                                    uPass = reader[2].ToString();
                                    uSt   = reader[3].ToString();
                                }
                            }
                        }
                    }
                }

                if (uName is null || string.IsNullOrEmpty(uName) || (uName ?? "") == (string.Empty ?? ""))
                {
                    return(false);
                }

                if (uSt is null || uSt == "0" || (uSt ?? "") == (string.Empty ?? ""))
                {
                    return(false);
                }

                if (!SimpleHash.VerifyHash(password, "SHA256", uPass))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }

            // Return username.Equals("admin", StringComparison.InvariantCultureIgnoreCase) AndAlso password.Equals("123456")
        }
 public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
 {
     if (!base.IsAuthorized(actionContext))
     {
         HandleUnauthorizedRequest(actionContext);
     }
     else
     {
         string tk      = string.Empty;
         var    re      = actionContext.Request;
         var    headers = re.Headers;
         string meth    = re.Method.ToString();
         if (headers.Contains("Authorization"))
         {
             tk = headers.GetValues("Authorization").FirstOrDefault();
         }
         if (tk.StartsWith("Bearer "))
         {
             tk = tk.Replace("Bearer ", "");
         }
         string stUri = actionContext.Request.RequestUri.AbsolutePath;
         VarsSubsFunc.AddCardexTokens(stUri, meth, (int)System.Net.HttpStatusCode.Accepted, nameof(System.Net.HttpStatusCode.Accepted), VarsSubsFunc.GetIpAddress().Trim(), tk);
     }
 }
Esempio n. 3
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string userN = string.Empty;

            // If IsSwagger(request) AndAlso Not request.IsLocal() Then
            if (IsSwagger(request))
            {
                request.Headers.TryGetValues("Authorization", out IEnumerable <string> authHeaderValues);
                string authHeader = authHeaderValues?.FirstOrDefault();
                if (authHeader is object && authHeader.StartsWith("Basic "))
                {
                    string encodedUsernamePassword = authHeader.Split(' ')[1]?.Trim();
                    string decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
                    string username = decodedUsernamePassword.Split(':')[0];
                    string password = decodedUsernamePassword.Split(':')[1];
                    userN = username;
                    if (IsAuthorized(username, password))
                    {
                        VarsSubsFunc.AddSwaggerCardex(request.RequestUri.PathAndQuery, (int)HttpStatusCode.Accepted, nameof(HttpStatusCode.Accepted), VarsSubsFunc.GetIpAddress().Trim(), userN);
                        return(await base.SendAsync(request, cancellationToken));
                    }
                }

                VarsSubsFunc.AddSwaggerCardex(request.RequestUri.PathAndQuery, (int)HttpStatusCode.Unauthorized, nameof(HttpStatusCode.Unauthorized), VarsSubsFunc.GetIpAddress().Trim(), userN);
                var response = request.CreateResponse(HttpStatusCode.Unauthorized);
                response.Headers.Add("WWW-Authenticate", "Basic");
                return(response);
            }
            else
            {
                // AddSwaggerCardex(request.RequestUri.PathAndQuery.ToString, Net.HttpStatusCode.Accepted, Net.HttpStatusCode.Accepted.ToString, GetIpAddress.Trim, userN)
                return(await base.SendAsync(request, cancellationToken));
            }
        }
        protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (!HttpContext.Current.User.Identity.IsAuthenticated)
            {
                base.HandleUnauthorizedRequest(actionContext);

                // {
                // "Message": "Authorization has been denied for this request."
                // }

                string tk      = string.Empty;
                var    re      = actionContext.Request;
                var    headers = re.Headers;
                string meth    = re.Method.ToString();
                if (headers.Contains("Authorization"))
                {
                    tk = headers.GetValues("Authorization").FirstOrDefault();
                }
                if (tk.StartsWith("Bearer "))
                {
                    tk = tk.Replace("Bearer ", "");
                }
                string stUri = actionContext.Request.RequestUri.AbsolutePath;
                VarsSubsFunc.AddCardexTokens(stUri, meth, (int)System.Net.HttpStatusCode.Unauthorized, nameof(System.Net.HttpStatusCode.Unauthorized), VarsSubsFunc.GetIpAddress().Trim(), tk);
                var    resp     = new { Message = "Authorization has been denied for this request." };
                string yourJson = JsonConvert.SerializeObject(resp);
                actionContext.Response = new System.Net.Http.HttpResponseMessage()
                {
                    StatusCode = System.Net.HttpStatusCode.Unauthorized,
                    Content    = new System.Net.Http.StringContent(yourJson, Encoding.UTF8, "application/json")
                };
            }
            else
            {
                string tk      = string.Empty;
                var    re      = actionContext.Request;
                var    headers = re.Headers;
                string meth    = re.Method.ToString();
                if (headers.Contains("Authorization"))
                {
                    tk = headers.GetValues("Authorization").FirstOrDefault();
                }
                if (tk.StartsWith("Bearer "))
                {
                    tk = tk.Replace("Bearer ", "");
                }
                string stUri = actionContext.Request.RequestUri.AbsolutePath;
                VarsSubsFunc.AddCardexTokens(stUri, meth, (int)System.Net.HttpStatusCode.Forbidden, nameof(System.Net.HttpStatusCode.Forbidden), VarsSubsFunc.GetIpAddress().Trim(), tk);
                actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
            }
        }