3 * IndieAuth to OpenID proxy.
4 * Proxies IndieAuth authorization requests to one's OpenID server
8 * @package indieauth-openid
9 * @author Christian Weiske <cweiske@cweiske.de>
10 * @license http://www.gnu.org/licenses/agpl.html GNU AGPL v3
11 * @link http://indiewebcamp.com/login-brainstorming
12 * @link http://indiewebcamp.com/authorization-endpoint
13 * @link http://indiewebcamp.com/auth-brainstorming
14 * @link https://indieauth.com/developers
16 header('IndieAuth: authorization_endpoint');
17 if (($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
24 require_once 'Net/URL2.php';
25 require_once 'OpenID.php';
26 require_once 'OpenID/RelyingParty.php';
27 require_once 'OpenID/Message.php';
28 require_once 'OpenID/Exception.php';
32 $pharFile = \Phar::running();
33 if ($pharFile == '') {
34 $dsn = 'sqlite:' . __DIR__ . '/../data/tokens.sq3';
35 $cfgFilePath = __DIR__ . '/config.php';
37 //remove phar:// from the path
38 $dir = dirname(substr($pharFile, 7)) . '/';
39 $dsn = 'sqlite:' . $dir . '/tokens.sq3';
40 $cfgFilePath = substr($pharFile, 7) . '.config.php';
42 //allow overriding DSN
43 if (file_exists($cfgFilePath)) {
48 $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
49 $db->exec("CREATE TABLE IF NOT EXISTS authtokens(
58 $stmt = $db->prepare('DELETE FROM authtokens WHERE created < :created');
59 $stmt->execute(array(':created' => date('c', time() - 60)));
64 function create_token($me, $redirect_uri, $client_id, $state)
66 $code = base64_encode(openssl_random_pseudo_bytes(32));
69 'INSERT INTO authtokens (code, me, redirect_uri, client_id, state, created)'
70 . ' VALUES(:code, :me, :redirect_uri, :client_id, :state, :created)'
75 ':redirect_uri' => $redirect_uri,
76 ':client_id' => $client_id,
77 ':state' => (string) $state,
78 ':created' => date('c')
84 function validate_token($code, $redirect_uri, $client_id)
88 'SELECT me FROM authtokens WHERE'
90 . ' AND redirect_uri = :redirect_uri'
91 . ' AND client_id = :client_id'
92 . ' AND created >= :created'
97 ':redirect_uri' => $redirect_uri,
98 ':client_id' => $client_id,
99 ':created' => date('c', time() - 60)
102 $row = $stmt->fetch(PDO::FETCH_ASSOC);
104 $stmt = $db->prepare('DELETE FROM authtokens WHERE code = :code');
105 $stmt->execute(array(':code' => $code));
107 if ($row === false) {
115 header('HTTP/1.0 400 Bad Request');
116 header('Content-type: text/plain; charset=utf-8');
121 function verifyUrlParameter($givenParams, $paramName)
123 if (!isset($givenParams[$paramName])) {
124 error('"' . $paramName . '" parameter missing');
126 $url = parse_url($givenParams[$paramName]);
127 if (!isset($url['scheme'])) {
128 error('Invalid URL in "' . $paramName . '" parameter: scheme missing');
130 if (!isset($url['host'])) {
131 error('Invalid URL in "' . $paramName . '" parameter: host missing');
134 return $givenParams[$paramName];
137 function getBaseUrl()
139 if (!isset($_SERVER['REQUEST_SCHEME'])) {
140 $_SERVER['REQUEST_SCHEME'] = 'http';
142 $file = preg_replace('/[?#].*$/', '', $_SERVER['REQUEST_URI']);
143 return $_SERVER['REQUEST_SCHEME'] . '://'
144 . $_SERVER['HTTP_HOST']
149 $returnTo = getBaseUrl();
150 $realm = getBaseUrl();
152 if (isset($_GET['openid_mode']) && $_GET['openid_mode'] != '') {
153 //verify openid response
154 if (!count($_POST)) {
155 list(, $queryString) = explode('?', $_SERVER['REQUEST_URI']);
157 $queryString = file_get_contents('php://input');
160 $message = new \OpenID_Message($queryString, \OpenID_Message::FORMAT_HTTP);
161 $id = $message->get('openid.claimed_id');
162 if (OpenID::normalizeIdentifier($id) != OpenID::normalizeIdentifier($_SESSION['me'])) {
165 'Given identity URL "%s" and claimed OpenID "%s" do not match',
171 $o = new \OpenID_RelyingParty($returnTo, $realm, $_SESSION['me']);
172 $result = $o->verify(new \Net_URL2($returnTo . '?' . $queryString), $message);
174 if ($result->success()) {
175 $token = create_token(
176 $_SESSION['me'], $_SESSION['redirect_uri'],
177 $_SESSION['client_id'], $_SESSION['state']
179 //redirect to indieauth
180 $url = new Net_URL2($_SESSION['redirect_uri']);
181 $url->setQueryVariable('code', $token);
182 $url->setQueryVariable('me', $_SESSION['me']);
183 $url->setQueryVariable('state', $_SESSION['state']);
184 header('Location: ' . $url->getURL());
187 error('Error verifying OpenID login: ' . $result->getAssertionMethod());
189 } catch (OpenID_Exception $e) {
190 error('Error verifying OpenID login: ' . $e->getMessage());
191 } catch (Exception $e) {
192 error(get_class($e) . ': ' . $e->getMessage());
196 if ($_SERVER['REQUEST_METHOD'] == 'GET') {
197 $me = verifyUrlParameter($_GET, 'me');
198 $redirect_uri = verifyUrlParameter($_GET, 'redirect_uri');
199 $client_id = verifyUrlParameter($_GET, 'client_id');
201 if (isset($_GET['state'])) {
202 $state = $_GET['state'];
204 $response_type = 'id';
205 if (isset($_GET['response_type'])) {
206 $response_type = $_GET['response_type'];
208 if ($response_type != 'id') {
209 error('unsupported response_type: ' . $response_type);
212 $_SESSION['me'] = $me;
213 $_SESSION['redirect_uri'] = $redirect_uri;
214 $_SESSION['client_id'] = $client_id;
215 $_SESSION['state'] = $state;
218 $o = new \OpenID_RelyingParty($returnTo, $realm, $me);
219 //if you get timeouts (errors like
220 // OpenID error: Request timed out after 3 second(s)
221 //) then uncomment the following line which disables
223 //$o->setRequestOptions(array('follow_redirects' => true));
224 $authRequest = $o->prepare();
225 $url = $authRequest->getAuthorizeURL();
226 header("Location: $url");
228 } catch (OpenID_Exception $e) {
229 error('OpenID error: ' . $e->getMessage());
230 } catch (Exception $e) {
231 error(get_class($e) . ': ' . $e->getMessage());
233 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
234 $redirect_uri = verifyUrlParameter($_POST, 'redirect_uri');
235 $client_id = verifyUrlParameter($_POST, 'client_id');
236 if (!isset($_POST['code'])) {
237 error('"code" parameter missing');
239 $token = $_POST['code'];
241 $me = validate_token($token, $redirect_uri, $client_id);
243 error('Validating token failed');
245 header('Content-type: application/x-www-form-urlencoded');
246 echo 'me=' . urlencode($me);