Completed
Push — master ( b9f86c...3cac6c )
by Basil
02:29
created

JsonCruftFilter::getCruftLength()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace luya\web\filters;
4
5
use Yii;
6
use yii\base\ActionFilter;
7
use yii\web\Response;
8
9
/**
10
 * Json Cruft Filter.
11
 * 
12
 * This ActionFilter will append the {{luya\web\filters\JsonCruftFilter::$cruft}} string before every request
13
 * in order to disallow json hijacking.
14
 * 
15
 * ```php
16
 * public function behaviors()
17
 * {
18
 *     return [
19
 *         'class' => luya\web\filters\JsonCruftFilter::class,
20
 *     ];
21
 * }
22
 * ```
23
 * 
24
 * On the client side (example using angular) you have to remove the cruft string from every response content
25
 * in order to have a valid json response.
26
 * 
27
 * @see http://blog.portswigger.net/2016/11/json-hijacking-for-modern-web.html
28
 * @see https://stackoverflow.com/a/3270390
29
 * @author Basil Suter <[email protected]>
30
 * @since 1.0.7
31
 */
32
class JsonCruftFilter extends ActionFilter
33
{
34
    /**
35
     * @var string The curft string which is appended to every json rest response.
36
     */
37
    public $cruft = 'throw 1;<dont be evil>';
38
    
39
    public function getCruftLength()
40
    {
41
        return strlen($this->cruft);
42
    }
43
    
44
    public function prependCruft($content)
45
    {
46
        return $this->cruft . trim($content);
47
    }
48
    
49
    public function afterAction($action, $result)
50
    {
51
        if (Yii::$app->response->format == Response::FORMAT_JSON) {
52
            return $this->prependCruft($result);    
53
        }
54
        
55
        return $result;
56
    }
57
}