Skip to content

Commit 54269d7

Browse files
Melhoria nos testes do Token.php e Authorizator.php.
1 parent ad0c611 commit 54269d7

File tree

6 files changed

+185
-36
lines changed

6 files changed

+185
-36
lines changed

src/Auth/Authorizator.php

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
use Zend\Mvc\OIDC\Common\Parse\ConfigurationParser;
1212
use Zend\ServiceManager\ServiceLocatorInterface;
1313
use Zend\ServiceManager\ServiceManager;
14-
use Zend\Stdlib\RequestInterface;
1514

1615
/**
1716
* Class Authorizator
@@ -79,11 +78,12 @@ public function authorize(Request $request): bool
7978

8079
private function isAuthorized(Token $token, array $authorizeConfig): bool
8180
{
82-
$result = true;
81+
$result = false;
82+
$claimName = $authorizeConfig['requireClaim'];
8383

84-
foreach ($authorizeConfig as $claim) {
85-
if (!$token->hasClaim($claim)) {
86-
$result = false;
84+
foreach ($authorizeConfig['values'] as $claimValue) {
85+
if ($token->hasClaim($claimName, $claimValue)) {
86+
$result = true;
8787
break;
8888
}
8989
}
@@ -95,14 +95,13 @@ private function getAuthorizeConfiguration(Request $request): array
9595
{
9696
$url = $request->getUriString();
9797

98-
if (isset($this->routesConfig[$url])) {
99-
if (isset($this->routesConfig[$url]['options']['defaults']['authorize'])) {
100-
return $this->routesConfig[$url]['options']['defaults']['authorize'];
101-
}
98+
if (isset($this->routesConfig[$url]) &&
99+
isset($this->routesConfig[$url]['options']['defaults']['authorize'])) {
100+
return $this->routesConfig[$url]['options']['defaults']['authorize'];
102101
}
103102

104103
return [];
105-
}
104+
}
106105

107106
/**
108107
* @param Request $request
@@ -115,8 +114,7 @@ private function getAuthorizationToken(Request $request): string
115114
$headers = $request->getHeaders('Authorization', null);
116115
$token = '';
117116

118-
if (!is_null($headers))
119-
{
117+
if (!is_null($headers)) {
120118
$token = $headers->toString();
121119
$token = str_replace('Authorization: Bearer', null, $token);
122120

src/Common/Configuration.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ class Configuration
2929
*/
3030
private $authServiceUrl;
3131

32+
/**
33+
* @var string
34+
*/
35+
private $audience;
36+
37+
3238
/**
3339
* @return string
3440
*/
@@ -101,4 +107,22 @@ public function setAuthServiceUrl(string $authServiceUrl): void
101107
{
102108
$this->authServiceUrl = $authServiceUrl;
103109
}
110+
111+
/**
112+
* @return string
113+
*/
114+
public function getAudience(): string
115+
{
116+
return $this->audience;
117+
}
118+
119+
/**
120+
* @param string $audience
121+
*/
122+
public function setAudience(string $audience): void
123+
{
124+
$this->audience = $audience;
125+
}
126+
127+
104128
}

src/Common/Model/Token.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,20 @@ public function validate(Configuration $configuration): int
5858
}
5959
}
6060

61-
public function hasClaim(string $value): bool
61+
public function hasClaim(string $name, string $value): bool
6262
{
63-
return $this->jwt->hasClaim($value);
63+
if ($this->jwt->hasClaim($name)) {
64+
return ($this->jwt->getClaim($name) === $value);
65+
}
66+
67+
return false;
6468
}
6569

6670
private function setValidationData(\DateTime $moment, Configuration $configuration): ValidationData
6771
{
6872
$data = new ValidationData($moment->getTimestamp());
6973
$data->setIssuer($configuration->getRealmUrl());
74+
$data->setAudience($configuration->getAudience());
7075

7176
return $data;
7277
}

tests/Auth/AuthorizatorTest.php

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,11 @@ class AuthorizatorTest extends TestCase
4848
*/
4949
private $issuer;
5050

51+
/**
52+
* @var string
53+
*/
54+
private $audience;
55+
5156
/**
5257
* setUp
5358
*/
@@ -79,6 +84,27 @@ public function testWhenAnUnauthorizedRequestIsMade(): void
7984
$module->onDispatch($this->mvcEvent);
8085
}
8186

87+
public function testWhenAnAuthorizedRequestIsMade(): void
88+
{
89+
$success = true;
90+
91+
try {
92+
$this->request->setUri('/auth/login');
93+
94+
$token = $this->createJwt('SpecialPerson');
95+
96+
$this->request->getHeaders()->addHeaderLine('Authorization', 'Bearer ' . $token);
97+
$this->mvcEvent->setRequest($this->request);
98+
99+
$module = new Module();
100+
$module->onDispatch($this->mvcEvent);
101+
} catch (AuthorizeException $ex) {
102+
$success = false;
103+
}
104+
105+
$this->assertTrue($success);
106+
}
107+
82108
private function createJwt(string $claim): \Lcobucci\JWT\Token
83109
{
84110
$this->now = new DateTime();
@@ -87,6 +113,7 @@ private function createJwt(string $claim): \Lcobucci\JWT\Token
87113

88114
$this->publicKey = 'file://' . $path;
89115
$this->issuer = 'http://issuedby.com/auth/realms/teste';
116+
$this->audience = 'pos-api.com';
90117

91118
$signer = new Sha256();
92119
$privateKey = new Key('file://teste.key');
@@ -96,7 +123,8 @@ private function createJwt(string $claim): \Lcobucci\JWT\Token
96123
->issuedAt($this->now->getTimestamp())
97124
->canOnlyBeUsedAfter($this->now->getTimestamp())
98125
->expiresAt($this->now->getTimestamp() + 60)
99-
->withClaim('user_role', $claim)
126+
->permittedFor($this->audience)
127+
->withClaim('user_roles', $claim)
100128
->getToken($signer, $privateKey);
101129
}
102130
}

tests/Common/Model/TokenTest.php

Lines changed: 91 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,6 @@
1818
*/
1919
class TokenTest extends TestCase
2020
{
21-
/**
22-
* @var Token
23-
*/
24-
private $token;
2521

2622
/**
2723
* @var string
@@ -46,10 +42,6 @@ public function setUp()
4642

4743
$this->publicKey = 'file://' . $path;
4844
$this->issuer = 'http://issuedby.com/auth/realms/teste';
49-
50-
$jwt = $this->createJwt();
51-
52-
$this->token = new Token($jwt);
5345
}
5446

5547
private function createJwt(): \Lcobucci\JWT\Token
@@ -62,6 +54,7 @@ private function createJwt(): \Lcobucci\JWT\Token
6254
->issuedAt($this->now->getTimestamp())
6355
->canOnlyBeUsedAfter($this->now->getTimestamp())
6456
->expiresAt($this->now->getTimestamp() + 60)
57+
->permittedFor('pos-api.com')
6558
->getToken($signer, $privateKey);
6659
}
6760

@@ -72,9 +65,14 @@ public function testValidateWithCorrectIssuerClaimTokenShouldReturnValidResult()
7265
$configuration->setPublicKey($this->publicKey);
7366
$configuration->setRealmId('teste');
7467
$configuration->setAuthServiceUrl('http://issuedby.com');
68+
$configuration->setAudience('pos-api.com');
69+
70+
$jwt = $this->createJwt();
71+
72+
$token = new Token($jwt);
7573

7674
// act
77-
$result = $this->token->validate($configuration);
75+
$result = $token->validate($configuration);
7876

7977
// assert
8078
$this->assertEquals(ValidationTokenResultEnum::VALID, $result);
@@ -87,9 +85,92 @@ public function testValidateWithIncorrectIssuerClaimShouldReturnInvalidResult()
8785
$configuration->setPublicKey($this->publicKey);
8886
$configuration->setRealmId('teste');
8987
$configuration->setAuthServiceUrl('http://issuedby.com/bla/bla');
88+
$configuration->setAudience('pos-api.com');
89+
90+
$jwt = $this->createJwt();
91+
92+
$token = new Token($jwt);
93+
94+
// act
95+
$result = $token->validate($configuration);
96+
97+
// assert
98+
$this->assertEquals(ValidationTokenResultEnum::INVALID, $result);
99+
}
100+
101+
public function testValidateWithIncorrectAudienceClaimShouldReturnInvalidResult()
102+
{
103+
// arrange
104+
$configuration = new Configuration();
105+
$configuration->setPublicKey($this->publicKey);
106+
$configuration->setRealmId('teste');
107+
$configuration->setAuthServiceUrl('http://issuedby.com');
108+
$configuration->setAudience('wrong.pos-api.com');
109+
110+
$jwt = $this->createJwt();
111+
112+
$token = new Token($jwt);
113+
114+
// act
115+
$result = $token->validate($configuration);
116+
117+
// assert
118+
$this->assertEquals(ValidationTokenResultEnum::INVALID, $result);
119+
}
120+
121+
public function testValidateWithExpiredTokenShouldReturnExpiredResult()
122+
{
123+
// arrange
124+
$configuration = new Configuration();
125+
$configuration->setPublicKey($this->publicKey);
126+
$configuration->setRealmId('teste');
127+
$configuration->setAuthServiceUrl('http://issuedby.com');
128+
$configuration->setAudience('wrong.pos-api.com');
129+
130+
$signer = new Sha256();
131+
$privateKey = new Key('file://teste.key');
132+
133+
$jwt = (new Builder())
134+
->issuedBy($this->issuer)
135+
->issuedAt($this->now->getTimestamp() - 10)
136+
->canOnlyBeUsedAfter($this->now->getTimestamp() - 9)
137+
->expiresAt($this->now->getTimestamp() - 9)
138+
->permittedFor('pos-api.com')
139+
->getToken($signer, $privateKey);
140+
141+
$token = new Token($jwt);
142+
143+
// act
144+
$result = $token->validate($configuration);
145+
146+
// assert
147+
$this->assertEquals(ValidationTokenResultEnum::EXPIRED, $result);
148+
}
149+
150+
public function testValidateWithInvalidNotBeforeClaimShouldReturnInvalidResult()
151+
{
152+
// arrange
153+
$configuration = new Configuration();
154+
$configuration->setPublicKey($this->publicKey);
155+
$configuration->setRealmId('teste');
156+
$configuration->setAuthServiceUrl('http://issuedby.com');
157+
$configuration->setAudience('wrong.pos-api.com');
158+
159+
$signer = new Sha256();
160+
$privateKey = new Key('file://teste.key');
161+
162+
$jwt = (new Builder())
163+
->issuedBy($this->issuer)
164+
->issuedAt($this->now->getTimestamp())
165+
->canOnlyBeUsedAfter($this->now->getTimestamp() - 9)
166+
->expiresAt($this->now->getTimestamp() + 60)
167+
->permittedFor('pos-api.com')
168+
->getToken($signer, $privateKey);
169+
170+
$token = new Token($jwt);
90171

91172
// act
92-
$result = $this->token->validate($configuration);
173+
$result = $token->validate($configuration);
93174

94175
// assert
95176
$this->assertEquals(ValidationTokenResultEnum::INVALID, $result);

tests/Shared/module.config.php

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,40 @@
55
return [
66
'auth_service' => [
77
'auth_service_url' => 'http://34.95.175.142:8080',
8-
'realmId' => 'bvcteste',
9-
'client_id' => 'demo-app',
10-
'public_key' => ''
8+
'realmId' => 'bvcteste',
9+
'client_id' => 'demo-app',
10+
'public_key' => '',
11+
'audience' => 'pos-api.com'
1112
],
12-
'router' => [
13+
'router' => [
1314
'routes' => [
1415
'/auth/login' => [
15-
'type' => Literal::class,
16+
'type' => Literal::class,
1617
'options' => [
17-
'route' => '/auth/login',
18+
'route' => '/auth/login',
1819
'defaults' => [
1920
'controller' => 'SomeController::class',
20-
'action' => 'login',
21-
'authorize' => [
22-
'Administrator',
23-
'SpecialPerson'
21+
'action' => 'login',
22+
'authorize' => [
23+
'requireClaim' => 'user_roles',
24+
'values' => [
25+
'Administrator',
26+
'SpecialPerson'
27+
]
2428
]
2529
],
2630
],
2731
],
28-
'whitelist' => [
32+
'policies' => [
33+
'Administrator' => [
34+
'requireClaim' => 'user_roles',
35+
'values' => [
36+
'read:person',
37+
'write:person'
38+
]
39+
]
40+
],
41+
'whitelist' => [
2942
'/login'
3043
]
3144
]

0 commit comments

Comments
 (0)