Issues (37)

example/server_resource.php (2 issues)

Labels
Severity
1
<?php
2
3
/**
4
 * Server side implementation for validate the token
5
 */
6
7
use Parroauth2\Client\ClientConfig;
8
use Parroauth2\Client\EndPoint\Introspection\IntrospectionResponse;
9
use Parroauth2\Client\Extension\JwtAccessToken\JwtAccessToken;
10
use Parroauth2\Client\Extension\RequiredScopeValidator;
11
use Parroauth2\Client\Provider\ProviderConfigPool;
12
use Parroauth2\Client\Provider\ProviderLoader;
13
use Psr\SimpleCache\CacheInterface;
14
15
require_once __DIR__.'/../vendor/autoload.php';
16
17
class Authenticator
18
{
19
    private const PROVIDER_URL = 'http://192.168.0.139/~vquatrevieux/sso/s2pweb/oidc';
20
    private const CLIENT_ID = 'server_resource_test';
21
    private const CLIENT_SECRET = 'my_secret';
22
23
    /**
24
     * @var \Parroauth2\Client\ClientInterface
25
     */
26
    private $client;
27
28
    /**
29
     * @var IntrospectionResponse
30
     */
31
    private $token;
32
33
    public function __construct(CacheInterface $cache)
34
    {
35
        // Load the provider and provide a cache for the config to ensure that
36
        // keys and config are stored locally, and the server will not perform any request to check the token
37
        $loader = new ProviderLoader(null, null, null, null, new ProviderConfigPool($cache));
38
39
        // Create the client
40
        $this->client = $loader->discover(self::PROVIDER_URL)->client(
41
            (new ClientConfig(self::CLIENT_ID))->setSecret(self::CLIENT_SECRET)
42
        );
43
44
        // Enable local introspection using JWT access token
45
        $this->client->register(new JwtAccessToken());
46
47
        // Resource owner should check for some required scopes.
48
        // Enable this extension to assert the given scope are provided in the access token.
49
        $this->client->register(new RequiredScopeValidator(['profile']));
50
    }
51
52
    /**
53
     * Validate the access token passed as "Authorization: Bearer" header
54
     *
55
     * Perform a local introspection if possible (a key has been configured, and the access token is effectively a JWT)
56
     *
57
     * @return bool true if the access token is valid
58
     *
59
     * @throws \Http\Client\Exception
60
     * @throws \Parroauth2\Client\Exception\Parroauth2Exception
61
     * @throws \Parroauth2\Client\Exception\UnsupportedServerOperation
62
     *
63
     * @psalm-assert-if-true !null $this->token()
64
     * @psalm-assert-if-fale null $this->token()
65
     */
66
    public function authenticate(): bool
67
    {
68
        // Check the Authorization header
69
        if (empty($_SERVER['HTTP_AUTHORIZATION'])) {
70
            return false;
71
        }
72
73
        $header = explode(' ', trim($_SERVER['HTTP_AUTHORIZATION']));
74
75
        if (count($header) !== 2 || strcasecmp($header[0], 'bearer') !== 0) {
76
            return false;
77
        }
78
79
        // Perform introspection on the token
80
        // No HTTP request should be performed here because local introspection is enabled
81
        $response = $this->client->endPoints()->introspection()
82
            ->accessToken($header[1])
83
            ->call()
84
        ;
85
86
        // The token is expired or invalid
87
        if (!$response->active()) {
88
            return false;
89
        }
90
91
        $this->token = $response;
92
93
        return true;
94
    }
95
96
    /**
97
     * Get the parsed token
98
     *
99
     * @return IntrospectionResponse|null
100
     */
101
    public function token(): ?IntrospectionResponse
102
    {
103
        return $this->token;
104
    }
105
}
106
107
$authenticator = new Authenticator(new MyCacheImplementation());
0 ignored issues
show
The type MyCacheImplementation was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
108
109
if (!$authenticator->authenticate()) {
110
    http_response_code(401);
111
    exit('Invalid access token');
112
}
113
114
// Get the user id from the token
115
$userId = $authenticator->token()->subject();
116
117
echo json_encode(loadFromUserId($userId));
0 ignored issues
show
The function loadFromUserId was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

117
echo json_encode(/** @scrutinizer ignore-call */ loadFromUserId($userId));
Loading history...
118