Catch 302 with Apache and return 401 instead

We currently have a shibboleth implementation that protects a certain path. However, because this path is actually an HTTP request (made with an AngularJS app using $http), shibboleth will try to "redirect" this request to the Identity Provider, but the browser simply interprets this as a dead request. It gets returned to AngularJS with status=-1 and no associated headers/data.

I would like to intercept this 302 and instead return a 401, and preferably be able to edit the response headers. Are there any ways to do this using Apache or Shibboleth?

Relevant blocks:

# Proxy all requests to WebLogic
<Location "/api">
    SetHandler weblogic-handler
    WLSRequest On
    WebLogicHost services.endpoint.com
    WebLogicPort 9002
</Location>

# For requests marked as protected, apply shibboleth
# If this block gets triggered, Shibboleth attempts redirect
# which does not work with our architecture
<Location "/api/protected">
     AuthType Shibboleth
     ShibRequireSession On
     ShibApplicationId default
     ShibExportAssertion On
     Require Shibboleth
</Location>

How it's used in AngularJS:

//API call to unprotected endpoint
$http.get('http://hosted.on.apache.com/api/getData');

//API call to protected endpoint - Shibboleth triggered
$http.get('http://hosted.on.apache.com/api/protected/getSecureData');

Trouble capturing HTTP Authentication and writing to file

I'm trying to record access attempts made via a .htaccess file to a log file, via PHP.

I am primarily using the guide found here.

PHP is enabled and confirmed to be working fine, the .htaccess file is working fine(at least as far as requiring authentication). mod_rewrite is installed and confirmed working, as is authz_groupfile. System is ubuntu 14.04 LTS. Access attempts are present in the apache logfile.

my .htaccess file:

ErrorDocument 401 /mydir/logins.php
RewriteEngine On
RewriteBase /
RewriteCond %{ENV:REDIRECT_STATUS} ^401$ [OR]
RewriteCond %{REQUEST_URI} ^/.*login*.php$
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},E=REMOTE_USER:%{ENV:REDIRECT_REMOTE_USER}]

<files logins.php>
AuthName "Protection"
AuthUserFile /mydir/.htpasswd
AuthGroupFile /dev/null
AuthType Basic
Require valid-user
</Files>

and logins.php (mostly taken from the above site)

<?php
define('LOGINS_LOG','/var/www/logins.log');

ob_start();
header("HTTP/1.1 401 Authorization Required",1);
header("Status: 401 Authorization Required",1);
echo '<p>Trimmed HTML</p>';
$password=base64_decode(str_replace('Basic ','', $_SERVER['HTTP_AUTHORIZATION']));
$fp = fopen(LOGINS_LOG, 'a+');
fwrite($fp, $_SERVER['PHP_AUTH_USER']."\n");
fclose($fp);
exit;
exit();
?>
fclose($fp);
echo $password;
exit;
exit();
?>

Now...I can't seem to get the credentials to write to the file at all. It isn't a permissions or path issue, as newlines are written to the file depending on which variable I attempt to write out...so far none have worked.

Now, the code on the page tries writing out the _ENV['REDIRECT_REMOTE_USER'] variable to file...however nothing was written, except maybe newlines.

I tried writing out the $password variable( created a few lines above where I try writing to file), as well as:

  • _SERVER['PHP_AUTH_USER']
  • _SERVER['PHP_AUTH_PASS']
  • _SERVER['HTTP_AUTHORIZATION']

In all cases, the only thing I get is newlines(which at least means that writing to file is happening), in some cases nothing at all.

Am I simply using the wrong variable to write to file, and if so what is the correct variable? Otherwise, what is the issue?

Launch a simple ruby application on AWS with Apache web server. (without using elastic beanstalk)

I'm just trying to launch a simple ruby application (displaying the welcome page of ruby). I am launching an ubuntu instance in AWS to perform this. Without turning on the apache2 i'm able to go to the page, when i turn it on, it shows "The page you were looking for doesn't exist. You may have mistyped the address or the page may have moved."

Attaching all the config and the error info.

Any help would be appreciated. Thank you.


database.yml

# SQLite version 3.x
#   gem install sqlite3
#
#   Ensure the SQLite 3 gem is defined in your Gemfile
#   gem 'sqlite3'
#
default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  database: db/production.sqlite3
[enter image description here][1]


  [1]: http://i.stack.imgur.com/9sOPS.png

The Gemfile, error, secrets.yml and database.yml are attached.

Forward to Glassfish with Apache HTTP Server

I have a VPS with the address x.y.z.k.

In the server I've installed Glassfish v4.1.1. By default is listening on port 8080 for http and 8181 for https.

I've also installed Apache HTTP server with the classic command

apt install apache2

and by default is listening on port 80. I've enable the proxy_mod and added the following rows in the 000-default.conf file inside the tags .

ProxyPass / http://x.y.z.k:8080/MyWebApp/
ProxyPassReverse / http://x.y.z.k:8080/MyWebApp/

All is working but the problem is that, the user in its browser address bar write "x.y.z.k" but after the apache processing, the user, inside the address bar see http://x.y.z.k:8080/MyWebApp/.

In which way I can avoid this behavior? What I want is that 1. The user write x.y.z.k in his browser. 2. The apache forward the user request to my Glassfish server 3. The user still continue to see the same address typed before to send the request(x.y.z.k).

I suppose the solution is easy but I'm searching without any luck. Thank you!

Apache rewrite /* to /#*

I need an Apache RewriteRule that can rewrite a URI in the form of example.org/page to example.org/#page. I currently have:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ #$1 [NE]

This does not work. The QSA flag does not make any difference.

However, when I append the R(edirect) flag I end up on the right page but the hashtag is visible to the user and I don't want that. I want some form of 'permalinks', where the site URI after loading is example.org/page.

How to improve speed in a server with a big directory size (20Gb) from many files (22,500)? [on hold]

I'm developing a website for a library inside an institution. This library has a separate system that uploads large amounts of files (.pdf) and the website provides links to these files. The problem is the speed of the website outside the institution: the server wait time (TTFB) exceeds 1.5 seconds. When the directory of the files is isolated from the connection, the wait time is almost 0.3 seconds, even with deny access in .htaccess file. The server has three internal IPs with two external IPs via NAT. The speed inside the institution is fast, similar to localhost.

How can improve the speed? It's only matter of server configuration? or can be matter of server network?

OS: Windows Server 2012 R2 / Web server: Apache 2.4 / PHP: 5.6 / Wordpress: 4.5.2

Thanks.

Hataorg.json.JSONException

I've got a error Json exception but I dont know how can ı fix this error Could you help me ?

  • My error:

    06-30 21:00:35.461 22275-22503/com.kaanforum4.stok E/Try-Catch Hatası: Hataorg.json.JSONException: Value

  • MY PHP FİLE:

    // veritabanı bağlantısını oluştur try{ $baglanti = new PDO("mysql:host=mysql.hostinger.web.tr;dbname=u984093771_andro;charset=utf8", "u984093771_andro", "arda2905"); $baglanti -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ print $e -> getMessage(); } $gir = $baglanti -> prepare("INSERT INTO veriler SET isim = :i, soy = :s, kadi = :k,sifre = :si,email = :e, gonderilme = :g"); $sql_giris = $gir -> execute(array("i" => $isim, "s" => $soy, "k" => $kadi,"si" => $sifre,"e" => $email, "g" => time())); if($sql_giris){ $data[] = array( "islem" => true ); }else{ $data[] = array( "islem" => false ); } // son hazırlanan veriyi json formatında ekrana bas. header("Content-type: application/json"); } ?>

My apps : MY ANDROİD APPs:

    package com.kaanforum4.stok;

import android.os.Looper;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.message.BufferedHeader;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main2Activity extends AppCompatActivity
{

    Button btn1;
    EditText isim,soy,kadi,sifre,email;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        btn1= (Button) findViewById(R.id.button3);
        isim= (EditText) findViewById(R.id.editText3);
        soy= (EditText) findViewById(R.id.editText4);
        kadi= (EditText) findViewById(R.id.editText7);
        sifre= (EditText) findViewById(R.id.editText5);
        email= (EditText) findViewById(R.id.editText6);
        btn1.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                gonder(isim.getText().toString(),soy.getText().toString(),kadi.getText().toString(),sifre.getText().toString(),email.getText().toString());
                // DATAYA VER›LER› CEKMEK ›«›N KULLANILICAK...
            }
        });
    }
        public void gonder(final String isim1 ,final String soy1,final String kadi1,final String sifre1,final String email1)
        {
            Thread t=new Thread()
            {
                public void run() {
                    Looper.prepare();
                    HttpClient client = new DefaultHttpClient();
                    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);//zaman a˛˝m˝ 10 sn
                    HttpResponse response;
                    try
                    {
                        HttpPost post =new HttpPost("http://androiduygulama.tk/kaydet.php");
                        List<NameValuePair> eklenecekler = new ArrayList<NameValuePair>(4);
                        eklenecekler.add(new BasicNameValuePair("isim",isim1));
                        eklenecekler.add(new BasicNameValuePair("soy",soy1));
                        eklenecekler.add(new BasicNameValuePair("kadi",kadi1));
                        eklenecekler.add(new BasicNameValuePair("sifre",sifre1));
                        eklenecekler.add(new BasicNameValuePair("email",email1));

                        post.setEntity(new UrlEncodedFormEntity(eklenecekler,"UTF-8"));
                        String html="";
                        response=client.execute(post);
                        if(response != null) {
                            InputStream in = response.getEntity().getContent();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                            StringBuilder sb = new StringBuilder();
                            String sat˝rlar = null;

                            try
                            {
                                    while ((sat˝rlar = reader.readLine())!= null)
                                    {
                                        sb.append(sat˝rlar+"\n");
                                    }
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                            }
                            finally
                            {
                                try
                                 {
                                    in.close();
                                 }
                                catch (IOException e)
                                 {
                                     e.printStackTrace();
                                 }
                            }
                            html=sb.toString();
                            JSONArray parcala=new JSONArray(html);
                            if(parcala.length()>0)
                            {
                                JSONObject obj =parcala.getJSONObject(0);
                                if(obj.getBoolean("islem")!= true)
                                {
                                    Toast.makeText(Main2Activity.this, "Bir Sorun Olu˛tu ve Kay˝t Yap˝lamad˝", Toast.LENGTH_SHORT).show();
                                }
                                else
                                {
                                    Toast.makeText(Main2Activity.this, "Kay˝t Ba˛ar˝ ile Tamamlamad˝", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Log.e("Try-Catch Hatas˝" ,"Hata"+e);
                    }
                    Looper.loop();
                }
            };
            t.start();
        }

}

Useless use of private variable in void context at {{path to perl file}}

I am trying to make a perl script that takes a remote hosts IP address when they visit a certain website. However I can't seem to get past this apache error: Useless use of private variable in void context at /var/www/html/src/cgi-bin/login.pl line 15., referer: ip_of_server:port/ This was the old error. IT happened when I would try to simply print $port;. The new one is on line 19 and says Permission denied at path_to_perl_script line 19.

I am running a website on an Ubuntu server and I have configured Apache2 and CGI properly.

Here is the login.pl script:

#!/usr/bin/perl -T
use CGI;
use DBI;
use strict;
use warnings;
use Path::Class;
use autodie;    

# read the CGI params
my $cgi = CGI->new;
my $username = $cgi->param("username");
my $password = $cgi->param("password");

my $port = $cgi->remote_host();

my $dir = dir("var/www/html");
my $file = dir->file("testingPerl.txt");
my $file_handle = $file->openw();
$file_handle->print($port);

I am fairly new to perl and I don't quite understand why I am getting this error.

Apache – how to use ProxyPass to route all outgoing requests to a different IP

I have an app running on Apache server, it listens on port 8000 for all incoming requests. When it sends outgoing requests, it might use a different port such as port 8888.

But now I want to use another server as a firewall (or load balancer ) so that all outgoing requests (HTTP/HTTPS/TCP/SSL) from my app will go to my firewall server first and then my firewall server will send them out.

I'm only concerned about outgoing requests now.

Is this achievable using Apache ProxyPass and ProxyPassReverse?

I tried below setting but it didn't work for me (x.x.x.x is my firewall server IP):

<VirtualHost *:8888>
  ServerName www.myapp.com
  SSLEngine on
  SSLCertificateFile /myapp.crt
  SSLCertificateKeyFile /myapp.key
  SSLCACertificateFile /myapp.pem
  SSLProxyEngine on
  SSLProxyCheckPeerCN off
  SSLProxyCheckPeerExpire off
  ProxyPreserveHost On
  ProxyPass / x.x.x.x
  ProxyPassReverse / x.x.x.x
</VirtualHost>

Please help.

Serve different code base on different devices browsing the same domain

I have web application built on PHP framework running on https://www.example.com which I'd like to target for only desktop users. For users, who are visiting https://www.example.com from mobile/tablet devices, I'd like to serve different application built on JS Framework but not redirecting them to different url. I am using AWS(Amazon web services) so solution specific to AWS will be greatly appreciated, but, any other solution will be a great help too.