整合 Persona 登入


記錄一下,整合到 Persona 服務的過程.

登入界面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
< !DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Persona Test</title>
<script language="javascript" src="https://login.persona.org/include.js"></script>
<script language="javascript">
(function(window) {
'use strict';

var initial = function() {
var login = function (assertion) {
if (assertion) {
document.location = 'login.php?assertion=' + assertion;
}
};

var connect = function (e) {
e.preventDefault();
window.navigator.id.get(login);
return false;
};

var loginControl = document.getElementById("loginControl");

if (loginControl.addEventListener) {
loginControl.addEventListener('click', connect, true);
}else if (loginBtn.attachEvent) {
loginControl.attachEvent('onclick', connect);
}
};

if (window.addEventListener) {
window.addEventListener('load', initial, false);
}else if (window.attachEvent) {
window.attachEvent('onload', initial);
}
})(window);
</script>
</head>
<body>
<button id="loginControl">Login</button>
</body>
</html>

登入處理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
require_once "persona.php";

$assertion = $_GET['assertion'] ?: "";

if (empty($assertion) === false) {
$result = Persona::verify($assertion);

if ($result === true) {
// User exists or not ...
// Make session or cookie by yourself ...

print_r(Persona::result());
}else{
print_r(Persona::reason());
}
}else{
echo "Please provide assertion value";
}
?>

Persona 驗證檢查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
class Persona {
private static $result = array();

public static function verify($assertion) {
static::$result = static::check($assertion);

return static::$result->status == 'okay';
}

public static function result() {
return static::$result;
}

public static function reason() {
return static::$result->reason;
}

private static function check($assertion) {
$post_field = http_build_query(array(
'assertion' => $assertion,
'audience' => $_SERVER['HTTP_HOST'],
));

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, "https://verifier.login.persona.org/verify");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post_field);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);

$result = curl_exec($curl);
curl_close($curl);

return json_decode($result);
}
}
?>