public Message(byte[] package)
        {
            string temp = new ASCIIEncoding().GetString(package);

            totalmessage = temp;
            temp         = temp.Trim();
            if (temp.StartsWith("<") && temp.EndsWith(">"))
            {
                temp = temp.Substring(1, temp.Length - 2);
                string[] strmsg = temp.Split(',');
                this.stationId = strmsg[0];
                this.MsgId     = Convert.ToInt32(strmsg[1]);
                this.MsgType   = (MsgType)strmsg[2][0];
                this.Info      = strmsg[3];
                if (strmsg.Length > 4)
                {
                    this.DutID = strmsg[4];
                }
                string[] strmsg2 = this.Info.Split(':');
                if (strmsg2[0] == "E")
                {
                    this.Info      = "E";
                    this.ErrorInfo = strmsg2[1];
                }
            }
        }
Exemple #2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="httpMethod">HTTP method to execute.</param>
 /// <param name="contentType"></param>
 /// <param name="path"></param>
 /// <param name="authHeader">Authentication header.</param>
 /// <param name="username">User name</param>
 /// <param name="password">Password.</param>
 /// <returns>True, if authentication was successful.</returns>
 /// <remarks>
 /// If authentication failed user name and password are empty strings.
 /// If authentication is not used user name and password are null.
 /// </remarks>
 internal static bool TryAuthenticate(Hashtable messageMap, string httpMethod, string contentType, string path, string authHeader, out string username, out string password)
 {
     if (NeedAuthentication(messageMap, httpMethod, contentType, path))
     {
         //Authorization header is checked if present.
         if (!string.IsNullOrEmpty(authHeader))
         {
             authHeader = authHeader.Trim();
             if (authHeader.IndexOf("Basic", 0) != 0)
             {
                 throw new Exception("Invalid authentication header.");
             }
             else
             {
                 authHeader = authHeader.Trim();
                 string   encodedCredentials = authHeader.Substring(6);
                 byte[]   decodedBytes       = Convert.FromBase64String(encodedCredentials);
                 string   s        = new ASCIIEncoding().GetString(decodedBytes);
                 string[] userPass = s.Split(new char[] { ':' });
                 username = userPass[0];
                 password = userPass[1];
                 return(true);
             }
         }
         else //If authentication is not given, but it's needed.
         {
             username = password = "";
             return(false);
         }
     }
     username = password = null;
     return(false);
 }
Exemple #3
0
        private string[] GetMessage(NetworkStream stream)
        {
            byte[] numArray = new byte[4096];
            int    count    = stream.Read(numArray, 0, 4096);
            string str      = new ASCIIEncoding().GetString(numArray, 0, count).Trim(new char[1]);

            Trace.Write((object)new LogInfo(LogType.Workflow, (Exception)null, " --> " + str));
            return(str.Split(new char[1]
            {
                '|'
            }, StringSplitOptions.None));
        }
Exemple #4
0
        void ExtractAuthToken(HttpContext context, out string username, out string password)
        {
            // The header is in the following format
            // "Basic 64BitEncodedUsernameAndPasswordString"
            // userAndPasswordDecoded is in the following
            // format "theusername:thepassword"
            var userAndPassDecoded = new ASCIIEncoding().GetString(
                Convert.FromBase64String(context.Request.Headers["Authorization"].Substring(6)));

            var userAndPasswordArray = userAndPassDecoded.Contains(":") ? userAndPassDecoded.Split(':') : new[] { userAndPassDecoded, "" };

            username = userAndPasswordArray[0];
            password = userAndPasswordArray[1];
        }
Exemple #5
0
        public void OnAuthenticateRequest2
        (
            object source
            , EventArgs eventArgs
        )
        {
            HttpApplication app = (HttpApplication)source;

            string authHeader = app.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    return;
                }

                authStr = authStr.Trim();

                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes =
                    Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string   username = userPass[0];
                string   password = userPass[1];

                if (!Validate(username, password))
                {
                    DenyAccess(app);
                    return;
                }
            }
            else
            {
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }
        public void ShowWebPage(Attachment att)
        {
            WebBrowser ctrl = new WebBrowser();

            ctrl.IsWebBrowserContextMenuEnabled = false;
            ctrl.ScriptErrorsSuppressed         = true;
            ctrl.WebBrowserShortcutsEnabled     = false;

            switch (att.Type)
            {
            case AttachmentType.URL:
            {
                string   str   = new ASCIIEncoding().GetString(att.Contents);
                string[] lines = str.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                string   url   = "";
                foreach (string line in lines)
                {
                    if (line.StartsWith("URL="))
                    {
                        url = line.Substring(4);
                        break;
                    }
                }

                if (url != "")
                {
                    ctrl.Navigate(url);
                }
            }
            break;

            case AttachmentType.HTML:
            {
                string str = new ASCIIEncoding().GetString(att.Contents);
                ctrl.DocumentText = str;
            }
            break;
            }

            Controls.Clear();
            Controls.Add(ctrl);
            ctrl.Dock = DockStyle.Fill;

            fMode = PlayerViewMode.HTML;

            Show();
        }
            private void ProcessBasicAuthRequest()
            {
                string authStr = HttpContext.Current.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    DenyAccess();
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    // Don't understand this header...we'll pass it along and
                    // assume someone else will handle it
                    DenyAccess();
                    return;
                }

                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                string s            = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string   username = userPass[0];
                string   password = userPass[1];

                UserInfo user = UserController.GetUserByUsernamePassword(
                    username, password, System.Web.HttpContext.Current.Request.UserHostAddress);

                if (user == null)
                {
                    // Invalid credentials; deny access
                    DenyAccess();
                    return;

                    //throw new Exception("Wrong BASIC credentials have been supplied");
                }

                SecurityContext.SetThreadPrincipal(user);
            }
 private static string[] GetDecodedAndSplitAuthorizatonHeader(
     string AuthHeader)
 {
     string[] RetVal = new string[2] {
         "", ""
     };
     if (AuthHeader != null && AuthHeader.StartsWith("Basic "))
     {
         try {
             string EncodedString = AuthHeader.Substring(6);
             byte[] DecodedBytes  = Convert.FromBase64String(EncodedString);
             string DecodedString = new ASCIIEncoding().GetString(DecodedBytes);
             RetVal = DecodedString.Split(new char[] { ':' });
         }
         catch {
         }
     }
     return(RetVal);
 }
        public bool Authorize(HttpContextBase context)
        {
            if (!SecurityContext.IsAuthenticated)
            {
                try
                {
                    //Try basic
                    var authorization = context.Request.Headers["Authorization"];
                    if (string.IsNullOrEmpty(authorization))
                    {
                        return(false);
                    }
                    authorization = authorization.Trim();
                    if (authorization.IndexOf(',') != -1)
                    {
                        authorization = authorization.Substring(0, authorization.IndexOf(',')).Trim();
                    }

                    if (authorization.IndexOf("Basic", 0) != 0)
                    {
                        return(false);
                    }

                    // cut the word "basic" and decode from base64
                    // get "username:password"
                    var tempConverted = Convert.FromBase64String(authorization.Substring(6));
                    var user          = new ASCIIEncoding().GetString(tempConverted);

                    // get "username"
                    // get "password"
                    var usernamePassword = user.Split(new[] { ':' });
                    var username         = usernamePassword[0];
                    var password         = usernamePassword[1];
                    _log.Debug("Basic Authorizing {0}", username);
                    Authentificate(username, password);
                }
                catch (Exception)
                {
                }
            }
            return(SecurityContext.IsAuthenticated);
        }
Exemple #10
0
        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;

            string authStr = app.Request.Headers["Authorization"];

            if (authStr == null || authStr.Length == 0)
            {
                // No credentials; anonymous request
                return;
            }

            authStr = authStr.Trim();
            if (authStr.IndexOf("Basic", 0) != 0)
            {
                // Don't understand this header...we'll pass it along and
                // assume someone else will handle it
                return;
            }

            string encodedCredentials = authStr.Substring(6);

            byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
            string s            = new ASCIIEncoding().GetString(decodedBytes);

            string[] userPass = s.Split(new char[] { ':' });
            string   username = userPass[0];
            string   password = userPass[1];

            string[] roles;
            if (AuthenticateUser(app, username, password, out roles))
            {
                app.Context.User = new GenericPrincipal(new GenericIdentity(username, "Basic"), roles);
            }
            else
            {
                // Invalid credentials; deny access
                DenyAccess(app);
                return;
            }
        }
        public static async Task <bool> AuthenticateRequestAsync(HttpActionContext actionContext)
        {
            bool isAuthorized = false;

            HttpRequestHeaders headers    = actionContext.Request.Headers;
            string             authScheme = headers.Authorization.Scheme;

            if (authScheme.Equals("Bearer"))
            {
                if (actionContext.RequestContext != null)
                {
                    ClaimsPrincipal claimsPrincipal = actionContext.RequestContext.Principal as ClaimsPrincipal;

                    if (claimsPrincipal != null && claimsPrincipal.Claims != null)
                    {
                        isAuthorized = CheckIfCallerClaimIsAuthorized(claimsPrincipal.Claims);
                    }
                }
                return(isAuthorized);
            }
            // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
            else if (authScheme.Equals("Basic"))
            {
                try
                {
                    string   decodedCredentials = new ASCIIEncoding().GetString(Convert.FromBase64String(headers.Authorization.Parameter));
                    string[] userPass           = decodedCredentials.Split(new char[] { ':' });
                    if (userPass[0].Equals(Settings.TenantId) && userPass[1].Equals(Settings.APISecretKey))
                    {
                        return(true);
                    }
                }
                catch
                {
                    return(false);
                }
            }
            return(false);
        }
Exemple #12
0
 private static string[] GetDecodedAndSplitAuthorizatonHeader(
     string AuthHeader)
 {
     string[] RetVal = new string[2] {
         string.Empty, string.Empty
     };
     if (AuthHeader != null && AuthHeader.StartsWith("Basic "))
     {
         try {
             string EncodedString = AuthHeader.Substring(6);
             byte[] DecodedBytes  = Convert.FromBase64String(EncodedString);
             string DecodedString = new ASCIIEncoding().GetString(DecodedBytes);
             RetVal = DecodedString.Split(new char[] { ':' });
         }
         catch (Exception ex) {
             Log.Err(
                 "BasicAuthenticationModule.GetDecodedAndSplitAuthorizatonHeader:"
                 + ex.Message);
         }
     }
     return(RetVal);
 }
        public static bool ProcessBasicAuthorization(HttpContext context, out string authCookie)
        {
            authCookie = null;
            try
            {
                //Try basic
                var authorization = context.Request.Headers["Authorization"];
                if (string.IsNullOrEmpty(authorization))
                {
                    return(false);
                }
                authorization = authorization.Trim();
                if (authorization.IndexOf("Basic", 0) != 0)
                {
                    return(false);
                }

                // cut the word "basic" and decode from base64
                // get "username:password"
                var tempConverted = Convert.FromBase64String(authorization.Substring(6));
                var user          = new ASCIIEncoding().GetString(tempConverted);

                // get "username"
                // get "password"
                var usernamePassword = user.Split(new[] { ':' });
                var username         = usernamePassword[0];
                var password         = usernamePassword[1];

                var userInfo = CoreContext.UserManager.GetUserByEmail(username);
                if (userInfo != null)
                {
                    authCookie = SecurityContext.AuthenticateMe(userInfo.ID.ToString(), password);
                }
            }
            catch (Exception) { }

            return(SecurityContext.IsAuthenticated);
        }
Exemple #14
0
        /// <summary>
        /// Authenticate user and check capability for the virtual directory.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        public void OnAuthenticateRequest(object sender, EventArgs e)
        {
            string          logPrefixOnAuthReq = this.LogPrefix + "OnAuthenticationRequest()";
            HttpApplication app = (HttpApplication)sender;

            try
            {
                string authHeader = app.Context.Request.Headers["Authorization"];
                authHeader = authHeader.TrimOrDefault();
                if (string.IsNullOrEmpty(authHeader))
                {
                    // Authorization header must be present...
                    this.LogDebug(string.Format("{0}: No basic authorization header found. Request basic authentication with 401 error and WWW-Authenticate header.", logPrefixOnAuthReq));
                    this.AddAuthenticateHeader(app);
                    app.CompleteRequest();
                    return;
                }

                if (authHeader.IndexOf("Basic", 0) != 0)
                {
                    // We don't understand this header if it doesn't start with 'Basic'...request basic authentication..
                    this.LogInfo(string.Format("{0}: No basic authentication. Request basic authentication with 401 error and WWW-Authenticate header.", logPrefixOnAuthReq));
                    this.AddAuthenticateHeader(app);
                    app.CompleteRequest();
                    return;
                }

                string encodedCredentials = authHeader.Substring(6);
                byte[] decodedBytes       = Convert.FromBase64String(encodedCredentials);
                string decodedCredentials = new ASCIIEncoding().GetString(decodedBytes);

                string[] userNameAndPwd = decodedCredentials.Split(new char[] { ':' });
                string   userName       = userNameAndPwd[0];
                string   password       = userNameAndPwd[1];

                // Decode path from url...
                string path = this.GetPathFromRequest(app.Context.Request);

                if (String.IsNullOrWhiteSpace(path))
                {
                    // Path is null or empty - deny access...
                    this.AccessDenied(app.Response);
                    app.CompleteRequest();
                    this.LogInfo(string.Format("{0}: User '{1}' denied for Path = '{2}'.", logPrefixOnAuthReq, userName, "Null or Empty"));
                    return;
                }

                // Do authentication...
                if (this.AuthenticateUser(userName, password) && this.CheckCapabilityForPathAndUser(path))
                {
                    // The user doesn't have to be set if Anonymous authentication is enabled...
                    app.Context.User = new GenericPrincipal(new GenericIdentity(userName, "CustomBasic"), null);

                    this.LogInfo(string.Format("{0}: User '{1}' authenticated for Path = '{2}', Identity.IsAuthenticated = {3}",
                                               logPrefixOnAuthReq, userName, path, app.Context.User.Identity.IsAuthenticated));

                    return;
                }
                else
                {
                    // Invalid credentials - deny access...
                    this.AccessDenied(app.Response);
                    app.CompleteRequest();
                    this.LogInfo(string.Format("{0}: User '{1}' denied for Path = '{2}'.", logPrefixOnAuthReq, userName, path));
                    return;
                }
            }
            catch (Exception ex)
            {
                this.LogError(string.Format("{0} - error: {1}", logPrefixOnAuthReq, ex.ToString()));
                this.AccessDenied(app.Response);
                app.CompleteRequest();
            }
        }
        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;

            //the Authorization header is checked if present
            string authHeader = app.Request.Headers["Authorization"];

            if (!string.IsNullOrEmpty(authHeader))
            {
                string authStr = app.Request.Headers["Authorization"];

                if (authStr == null || authStr.Length == 0)
                {
                    // No credentials; anonymous request
                    return;
                }

                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    // header is not correct...we'll pass it along and
                    // assume someone else will handle it
                    return;
                }


                authStr = authStr.Trim();


                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes =
                    Convert.FromBase64String(encodedCredentials);
                string s = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });
                string   username = userPass[0];
                string   password = userPass[1];

                Microsoft.Xrm.Client.CrmConnection connection = GetCrmConnection(username, password);
                using (OrganizationService service = new OrganizationService(connection))
                {
                    WhoAmIRequest  req  = new WhoAmIRequest();
                    WhoAmIResponse resp = (WhoAmIResponse)service.Execute(req);
                    if (resp.Results.Count > 0)
                    {
                        app.Context.User = new GenericPrincipal(new GenericIdentity(resp.UserId.ToString()), new string [] { "none" });
                    }
                    else
                    {
                        DenyAccess(app);
                        return;
                    }
                }

                if (Membership.ValidateUser(username, password))
                {
                    string[] roles = Roles.GetRolesForUser(username);
                }
                else
                {
                }
            }
            else
            {
                app.Response.StatusCode = 401;
                app.Response.End();
            }
        }
Exemple #16
0
        public void OnAuthenticateRequest(object source, EventArgs eventArgs)
        {
            HttpApplication app = (HttpApplication)source;


            string authStr  = app.Request.Headers["Authorization"];
            string username = string.Empty;
            string password = string.Empty;

            if (authStr == null || authStr.Length == 0)
            {
                // Check to see if anonymous access is allowed
                if (!AllowAnonymousAccess(app))
                {
                    DenyAccess(app);
                }

                // If we survive to here, anonymous access to current method of this resource is allowed
                return;
            }
            else
            {
                // LOOK FOR BASIC AUTH STRING
                authStr = authStr.Trim();
                if (authStr.IndexOf("Basic", 0) != 0)
                {
                    // Don't understand this header...we'll pass it along and
                    // assume someone else will handle it
                    DenyAccess(app);
                    return;
                }

                // DECRYPT AND UNSPIN USER AND PASSWORD
                string encodedCredentials = authStr.Substring(6);

                byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
                string s            = new ASCIIEncoding().GetString(decodedBytes);

                string[] userPass = s.Split(new char[] { ':' });

                username = userPass[0];
                password = userPass[1];
            }


            string cacheKey = string.Format("authentication.principal.{0}.{1}", username, password.GetHashCode());

            _userPrincipal = (GenericPrincipal)Cache.Get(cacheKey);
            if (_userPrincipal == null)
            {
                // USE THE PIPELINE TO INSTANCE THE RestNet_Authentication CLASS
                if (authClass == null)
                {
                    GetAuthClass();
                }

                try
                {
                    _userPrincipal = authClass.ProcessAuthentication(username, password);
                    //app.Context.User = _userPrincipal;
                    if (!_userPrincipal.Identity.IsAuthenticated)
                    {
                        DenyAccess(app);
                    }
                }
                catch (HttpException ex)
                {
                    DenyAccess(app, ex);
                }
                catch (System.Threading.ThreadAbortException)
                {
                    // DenyAccess already killed the request
                    return;
                }
                catch (Exception ex)
                {
                    RestNet.ErrorHandler.SendErrorResponse(app.Context.Response, ex);
                }

                if (_userPrincipal != null)
                {
                    Cache.Set(cacheKey, _userPrincipal, null, null, true, TimeSpan.FromMinutes(15));
                }
            }
        }
Exemple #17
0
    public void OnAuthenticateRequest(object source, EventArgs eventArgs)
    {
        HttpApplication app = (HttpApplication)source;
        // Get the request stream
        Stream httpStream = app.Request.InputStream;

        // I converted the stream to string so I can search for a known substring
        byte[] byteStream = new byte[httpStream.Length];
        httpStream.Read(byteStream, 0, (int)httpStream.Length);
        string strRequest = Encoding.ASCII.GetString(byteStream);
        // This is the end of the initial SOAP envelope
        // Not sure if the fastest way to do this but works fine
        int idx = strRequest.IndexOf("</t:RequestSecurityToken></s:Body></s:Envelope>", 0);

        httpStream.Seek(0, SeekOrigin.Begin);
        if (idx != -1)
        {
            // Initial packet found, do nothing (HTTP status code is set to 200)
            return;
        }
        //the Authorization header is checked if present
        string authHeader = app.Request.Headers["Authorization"];

        if (!string.IsNullOrEmpty(authHeader))
        {
            if (authHeader == null || authHeader.Length == 0)
            {
                // No credentials; anonymous request
                return;
            }
            authHeader = authHeader.Trim();
            if (authHeader.IndexOf("Basic", 0) != 0)
            {
                // the header doesn't contain basic authorization token
                // we will pass it along and
                // assume someone else will handle it
                return;
            }
            string   encodedCredentials = authHeader.Substring(6);
            byte[]   decodedBytes       = Convert.FromBase64String(encodedCredentials);
            string   s        = new ASCIIEncoding().GetString(decodedBytes);
            string[] userPass = s.Split(new char[] { ':' });
            string   username = userPass[0];
            string   password = userPass[1];
            // the user is validated against the SqlMemberShipProvider
            // If it is validated then the roles are retrieved from
            // the role provider and a generic principal is created
            // the generic principal is assigned to the user context
            // of the application
            if (Membership.ValidateUser(username, password))
            {
                string[] roles = Roles.GetRolesForUser(username);
                app.Context.User = new GenericPrincipal(new
                                                        GenericIdentity(username, "Membership Provider"), roles);
            }
            else
            {
                DenyAccess(app);
                return;
            }
        }
        else
        {
            app.Response.StatusCode = 401;
            app.Response.End();
        }
    }