Completed
Pull Request — develop (#110)
by Daan van
10:17 queued 07:23
created

ProcessSamlAuthenticationHandler   B

Complexity

Total Complexity 11

Size/Duplication

Total Lines 142
Duplicated Lines 11.97 %

Coupling/Cohesion

Components 1
Dependencies 16

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
c 1
b 0
f 0
lcom 1
cbo 16
dl 17
loc 142
rs 8.4614

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 17 17 1
C process() 0 76 9
A setNext() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
/**
4
 * Copyright 2016 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupSelfService\SelfServiceBundle\Security\Authentication\Handler;
20
21
use Exception;
22
use SAML2_Response_Exception_PreconditionNotMetException as PreconditionNotMetException;
23
use Surfnet\SamlBundle\Http\Exception\AuthnFailedSamlResponseException;
24
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
25
use Surfnet\SamlBundle\SAML2\Response\Assertion\InResponseTo;
26
use Surfnet\StepupSelfService\SelfServiceBundle\Security\Authentication\AuthenticatedSessionStateHandler;
27
use Surfnet\StepupSelfService\SelfServiceBundle\Security\Authentication\SamlAuthenticationStateHandler;
28
use Surfnet\StepupSelfService\SelfServiceBundle\Security\Authentication\SamlInteractionProvider;
29
use Surfnet\StepupSelfService\SelfServiceBundle\Security\Authentication\Token\SamlToken;
30
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
31
use Symfony\Component\HttpFoundation\RedirectResponse;
32
use Symfony\Component\HttpFoundation\Response;
33
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
34
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
35
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
36
use Symfony\Component\Security\Core\Exception\AuthenticationException;
37
38
/**
39
 * @SuppressWarnings(PHPMD.CouplingBetweeObjects) SamlResponse parsing, validation authentication and error handling
40
 *                                                requires quite a few classes as it is fairly complex.
41
 */
42
class ProcessSamlAuthenticationHandler implements AuthenticationHandler
43
{
44
    /**
45
     * @var AuthenticationHandler
46
     */
47
    private $nextHandler;
48
49
    /**
50
     * @var TokenStorageInterface
51
     */
52
    private $tokenStorage;
53
54
    /**
55
     * @var SamlInteractionProvider
56
     */
57
    private $samlInteractionProvider;
58
59
    /**
60
     * @var SamlAuthenticationStateHandler
61
     */
62
    private $authenticationStateHandler;
63
64
    /**
65
     * @var AuthenticatedSessionStateHandler
66
     */
67
    private $authenticatedSession;
68
69
    /**
70
     * @var AuthenticationManagerInterface
71
     */
72
    private $authenticationManager;
73
74
    /**
75
     * @var SamlAuthenticationLogger
76
     */
77
    private $authenticationLogger;
78
79
    /**
80
     * @var EngineInterface
81
     */
82
    private $templating;
83
84 View Code Duplication
    public function __construct(
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
85
        TokenStorageInterface $tokenStorage,
86
        SamlInteractionProvider $samlInteractionProvider,
87
        SamlAuthenticationStateHandler $authenticationStateHandler,
88
        AuthenticatedSessionStateHandler $authenticatedSession,
89
        AuthenticationManagerInterface $authenticationManager,
90
        SamlAuthenticationLogger $authenticationLogger,
91
        EngineInterface $templating
92
    ) {
93
        $this->tokenStorage               = $tokenStorage;
94
        $this->samlInteractionProvider    = $samlInteractionProvider;
95
        $this->authenticationStateHandler = $authenticationStateHandler;
96
        $this->authenticatedSession       = $authenticatedSession;
97
        $this->authenticationManager      = $authenticationManager;
98
        $this->authenticationLogger       = $authenticationLogger;
99
        $this->templating                 = $templating;
100
    }
101
102
    public function process(GetResponseEvent $event)
103
    {
104
        if ($this->tokenStorage->getToken() === null
105
            && $this->samlInteractionProvider->isSamlAuthenticationInitiated()
106
        ) {
107
            $expectedInResponseTo = $this->authenticationStateHandler->getRequestId();
108
            $logger               = $this->authenticationLogger->forAuthentication($expectedInResponseTo);
109
110
            $logger->notice('No authenticated user and AuthnRequest pending, attempting to process SamlResponse');
111
112
            try {
113
                $assertion = $this->samlInteractionProvider->processSamlResponse($event->getRequest());
114
            } catch (AuthnFailedSamlResponseException $exception) {
115
                $logger->notice(sprintf('SAML Authentication failed at IdP: "%s"', $exception->getMessage()));
116
                $responseBody = $this->templating->render(
117
                    'SurfnetStepupSelfServiceSelfServiceBundle:Saml/Exception:authnFailed.html.twig',
118
                    ['exception' => $exception]
119
                );
120
121
                $event->setResponse(new Response($responseBody, Response::HTTP_UNAUTHORIZED));
122
123
                return;
124
            } catch (PreconditionNotMetException $exception) {
125
                $logger->notice(sprintf('SAMLResponse precondition not met: "%s"', $exception->getMessage()));
126
                $responseBody = $this->templating->render(
127
                    'SurfnetStepupSelfServiceSelfServiceBundle:Saml/Exception:preconditionNotMet.html.twig',
128
                    ['exception' => $exception]
129
                );
130
131
                $event->setResponse(new Response($responseBody, Response::HTTP_UNAUTHORIZED));
132
133
                return;
134
            } catch (Exception $exception) {
135
                $logger->error(sprintf('Failed SAMLResponse Parsing: "%s"', $exception->getMessage()));
136
137
                throw new AuthenticationException('Failed SAMLResponse parsing', 0, $exception);
138
            }
139
140
            if (!InResponseTo::assertEquals($assertion, $expectedInResponseTo)) {
141
                $logger->error('Unknown or unexpected InResponseTo in SAMLResponse');
142
143
                throw new AuthenticationException('Unknown or unexpected InResponseTo in SAMLResponse');
144
            }
145
146
            $logger->notice('Successfully processed SAMLResponse, attempting to authenticate');
147
148
            $token            = new SamlToken();
149
            $token->assertion = $assertion;
150
151
            try {
152
                $authToken = $this->authenticationManager->authenticate($token);
153
            } catch (AuthenticationException $failed) {
154
                $logger->error(sprintf('Authentication Failed, reason: "%s"', $failed->getMessage()));
155
156
                // By default deny authorization
157
                $event->setResponse(new Response('', Response::HTTP_FORBIDDEN));
158
159
                return;
160
            }
161
162
            $this->tokenStorage->setToken($authToken);
163
164
            // migrate the session to prevent session hijacking
165
            $this->authenticatedSession->migrate();
166
167
            $event->setResponse(new RedirectResponse($this->authenticatedSession->getCurrentRequestUri()));
168
169
            $logger->notice('Authentication succeeded, redirecting to original location');
170
171
            return;
172
        }
173
174
        if ($this->nextHandler) {
175
            $this->nextHandler->process($event);
176
        }
177
    }
178
179
    public function setNext(AuthenticationHandler $handler)
180
    {
181
        $this->nextHandler = $handler;
182
    }
183
}
184