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

JsonCruftFilter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 26
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getCruftLength() 0 4 1
A prependCruft() 0 4 1
A afterAction() 0 8 2
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
}