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
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
diff --git a/src/flask_oauth2_validation/__init__.py b/src/flask_oauth2_validation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..01b48ce9eb368e39b20b4781ac59b976b4a3a97b
--- /dev/null
+++ b/src/flask_oauth2_validation/__init__.py
@@ -0,0 +1 @@
+from .decorator import OAuth2Decorator
diff --git a/src/flask_oauth2_validation/decorator.py b/src/flask_oauth2_validation/decorator.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1bcf41383e48a45e4abaf425923673240e55a93
--- /dev/null
+++ b/src/flask_oauth2_validation/decorator.py
@@ -0,0 +1,493 @@
+import base64
+import json
+import logging
+import requests
+import time
+import threading
+
+from flask import Flask, request
+from flask_executor import Executor
+from functools import wraps
+from jwt import JWT, jwk_from_dict
+from jwt.exceptions import JWTDecodeError
+
+from .exceptions import OAuth2Exception
+from .exceptions import OAuth2BadRequestException
+from .exceptions import OAuth2InsufficientScopeException
+from .exceptions import OAuth2InvalidTokenException
+
+
+class OAuth2Decorator():
+    """ This Flask view function decorator provides local and remote
+    OAuth2 (RFC-6749) validation for self-encoded JWT (RFC-7519) based
+    Bearer (RFC-6750) access tokens.
+
+    The minimal configuration expects the OAUTH2_ISSUER attribute being set
+    which points to the issuer::
+
+        app.config['OAUTH2_ISSUER'] = 'https://<your-issuer>/oauth2'
+
+    This would perform local token validation after downloading the public
+    keys (RFC-7517) from the authorization server (RFC-7800).
+
+    In case you also need to perform remote token validation (RFC-7662)
+    an OAUTH2_CLIENT_ID and OAUTH2_CLIENT_SECRET need to be configured::
+
+        app.config['OAUTH2_CLIENT_ID'] = 'your-client-id'
+        app.config['OAUTH2_CLIENT_SECRET'] = 'your-client-secret'
+
+    In case your authorization server uses rotating public keys an
+    OAUTH2_JWKS_UPDATE_INTERVAL (in seconds) could be configured to regularly
+    download the latest public keys from the authorization server::
+
+        app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 3600
+
+    For a more strict validation it is recommended to configure an
+    OAUTH2_AUDIENCE to verify the token against::
+
+        app.config['OAUTH2_AUDIENCE'] = 'api://default'
+
+    """
+
+    def __init__(self, app: Flask):
+        """ Reads the app configuration and requests
+        the Authorization Server Metadata as well as the
+        authorization servers public keys.
+
+        In case an auto reload of public keys has been
+        configured a flask executor is being initialized.
+        Whenever the last update is older than the configured
+        refresh interval a next incoming request would trigger
+        an async pubkey update request to the authorization
+        server.
+
+        In case remote validation is configured a request
+        will be sent to lookup the supported introspection
+        auth methods in addition.
+        """
+
+        self._logger = logging.getLogger(__name__)
+
+        app.config.setdefault('OAUTH2_ISSUER', None)
+        app.config.setdefault('OAUTH2_AUDIENCE', None)
+        app.config.setdefault('OAUTH2_JWKS_UPDATE_INTERVAL', None)
+        app.config.setdefault('OAUTH2_CLIENT_ID', None)
+        app.config.setdefault('OAUTH2_CLIENT_SECRET', None)
+
+        # Holds the current requests token in case
+        # the verification steps where all successful.
+        self.token = None
+
+        self._jwt = None
+        self._issuer = None
+        self._issuer_public_keys = None
+        self._audience = None
+        self._jwks_uri = None
+        self._jwks_update_interval = None
+        self._jwks_last_update_timestamp = None
+        self._jwks_update_mutex = threading.Lock()
+        self._executor = None
+        self._client_id = None
+        self._client_secret = None
+        self._introspection_endpoint = None
+        self._introspection_auth_method = None
+
+        # We only want to send out the request to the
+        # authorization server metadata endpoint once
+        # that's why we cache its response, here.
+        self._cached_metadata = None
+
+        # The only mandatory value is the issuer URI.
+        # In case it is the only value we expect it to offer
+        # Authorization Server Metadata support (RFC-8414).
+        if not app.config.get('OAUTH2_ISSUER'):
+            raise TypeError('An OAUTH2_ISSUER config property is required')
+        self._issuer = app.config.get('OAUTH2_ISSUER')
+
+        # In case we have a client id we assume that we will use the
+        # introspect endpoint.
+        self._client_id = app.config.get('OAUTH2_CLIENT_ID')
+        if self._client_id:
+            self._client_secret = app.config.get('OAUTH2_CLIENT_SECRET')
+            if not self._client_secret:
+                raise TypeError(
+                    'OAUTH2_CLIENT_SECRET config property required'
+                )
+
+        # We are supposed to validate self encoded tokens
+        # but don't have a pubkey and don't know the jwks_uri.
+        # Then we need to retrieve it from the authorization
+        # metadata endpoint
+        self._jwks_uri = self._lookup_metadata('jwks_uri')
+
+        # If an audience has been defined the JWT
+        # token 'aud' attribute will be validated
+        # against it
+        self._audience = app.config.get('OAUTH2_AUDIENCE')
+
+        # We're looking up the public keys from the
+        # authorization server and specifying the
+        # update interval to refresh the keys
+        # regularly during runtime (if set)
+        self._lookup_keys()
+        self._jwks_last_update_timestamp = time.time()
+        self._jwt = JWT()
+        self._jwks_update_interval = app.config.get(
+            'OAUTH2_JWKS_UPDATE_INTERVAL'
+        )
+        if self._jwks_update_interval:
+            self._executor = Executor(app, 'oauth2_jwks_update_task')
+
+        # In case we have a client_id and client_secret being set
+        # we can use the introspection endpoint.
+        if self._client_id and self._client_secret:
+
+            # We need to look up the introspection endpoint from
+            # the authorization server metadata.
+            self._introspection_endpoint = self._lookup_metadata(
+                'introspection_endpoint'
+            )
+
+            # Determine the auth method the introspection endpoint
+            # supports (basic or post are implemented so far):
+            server_supported_auth_methods = self._lookup_metadata(
+                'introspection_endpoint_auth_methods_supported'
+            )
+            if 'client_secret_post' in server_supported_auth_methods:
+                self._introspection_auth_method = 'client_secret_post'
+            elif 'client_secret_basic' in server_supported_auth_methods:
+                self._introspection_auth_method = 'client_secret_basic'
+            else:
+                raise TypeError(
+                    'The introspection auth methods are not supported: '
+                    + ' '.join(server_supported_auth_methods)
+                )
+
+    def _lookup_metadata(self, key: str) -> str:
+        """ Requests metadata information from an authorization endpoint
+        according to RFC-8414.
+        """
+        try:
+            if not self._cached_metadata:
+                metadata_uri = self._issuer + \
+                    '/.well-known/oauth-authorization-server'
+                self._logger.debug(
+                    f'Reading  metadata from {metadata_uri}',
+                )
+                response = requests.get(metadata_uri)
+                if not response.status_code == 200:
+                    raise TypeError(
+                        str(response.status_code)
+                    )
+                metadata = response.json()
+                self._cached_metadata = metadata
+            else:
+                metadata = self._cached_metadata
+            if key in metadata:
+                return metadata[key]
+            raise TypeError(
+                'No attribute '
+                + key
+                + ' found in authorization server metadata'
+            )
+        except BaseException as http_error:
+            raise TypeError(
+                'Cannot request authorization server metadata: '
+                + str(http_error)
+            )
+
+    def _lookup_keys(self) -> dict:
+        """ Downloads the public keys from an authorization server
+        according to RFC-7517.
+        """
+        try:
+            self._logger.debug(
+                f'Downloading public keys from {self._jwks_uri}'
+            )
+            response = requests.get(self._jwks_uri)
+            if not response.status_code == 200:
+                raise TypeError(
+                    f'Cannot request public keys from {self._jwks_uri}: '
+                    + str(response.status_code)
+                )
+            jwks_metadata = response.json()
+            if 'keys' in jwks_metadata:
+                keys = jwks_metadata['keys']
+                retrieved_keys = {}
+                for key in keys:
+                    if 'kid' in key:
+                        retrieved_keys[key['kid']] = key
+                self._issuer_public_keys = retrieved_keys
+        except BaseException as http_error:
+            raise TypeError(
+                'Cannot request public keys from '
+                + self._jwks_uri
+                + ': '
+                + str(http_error)
+            )
+
+    def _handle_token(self, fn, *args, **kwargs):
+        """ OAuth2 decorator logic which is being executed
+        whenever a decorated view function gets invoked.
+        """
+        introspect = kwargs['introspect']
+        scopes = kwargs['scopes']
+        # In case the decorated view function raises an exception
+        # it will be stored, here so that we can pass it down in a
+        # proper way, later.
+        decorated_exception = None
+        try:
+            # First we trigger a pubkey reload in case the time is up.
+            if self._executor:
+                self._executor.submit(self._update_keys)
+            # Then we extract read the Bearer token from the request.
+            if not request.headers.get('Authorization', None):
+                return OAuth2BadRequestException(
+                    'Authorization header missing'
+                ).response()
+            token = self._extract_token(request.headers['Authorization'])
+            if not token:
+                return OAuth2BadRequestException(
+                    'Bearer access token missing'
+                ).response()
+            # In case we could successfully read a Bearer token from the
+            # request we can finally validate it.
+            if self._is_valid(token, introspect, scopes):
+                kwargs.pop('scopes', None)
+                kwargs.pop('introspect', None)
+                try:
+                    # Only invoke the decorated view funtion in case
+                    # the token is valid.
+                    return fn(*args, **kwargs)
+                except Exception as decorated_error:
+                    # We will handle this exception later after we
+                    # handled our own OAuth2 validation related
+                    # exceptions
+                    decorated_exception = decorated_error
+            else:
+                return OAuth2InvalidTokenException(
+                    'Invalid token'
+                ).response()
+        except OAuth2Exception as oauth2_exception:
+            return oauth2_exception.response()
+        except BaseException as error:
+            self._logger.error(str(error))
+            return OAuth2InvalidTokenException(
+                'Token validation failed'
+            ).response()
+        # Finally handle possible exceptions risen from
+        # the decorated view function.
+        if decorated_exception:
+            raise decorated_exception
+
+    def _extract_token(self, authorization_header: str):
+        """ Extracts the Bearer access token from the HTTP
+        request header.
+        """
+        if not authorization_header.startswith('Bearer '):
+            return None
+        return authorization_header.split(sep=' ')[1]
+
+    def _is_valid(self, token: str, introspect: bool, scopes: list) -> bool:
+        """ First performs a local validation (always-on). And afterwards
+        a remote validation if configured.
+        """
+        if introspect and (not self._client_id or not self._client_secret):
+            raise OAuth2InvalidTokenException('Invalid configuration')
+        # First perform a local valiation
+        valid = self._validate_jwt(token, scopes)
+        if valid and introspect:
+            # Then in case introspection is required perform a
+            # remote validation in addition
+            valid = valid and self._request_introspection(token)
+        return valid
+
+    def _request_introspection(self, token: str) -> bool:
+        """ Sends the token introspection request to the
+        authorization server.
+        """
+        token_parameters = {
+            'token': token,
+        }
+        # We only support two introspection auth
+        # methods: client_secret_post ...
+        if self._introspection_auth_method == 'client_secret_post':
+            token_parameters['client_id'] = self._client_id
+            token_parameters['client_secret'] = self._client_secret
+        token_headers = {
+            'Accept': 'application/json',
+            'Content-Type': 'application/x-www-form-urlencoded'
+        }
+        # ... and client_secret_basic.
+        if self._introspection_auth_method == 'client_secret_basic':
+            token_headers['Authentication'] = 'Basic ' + \
+                base64.b64encode(bytes(
+                    self._client_id + ':' + self._client_secret,
+                    encoding='utf-8'
+                )).decode(encoding='utf-8')
+        response = requests.post(
+            url=self._introspection_endpoint,
+            data=token_parameters,
+            headers=token_headers
+        )
+        if not response.status_code == 200:
+            self._logger.error(
+                f'Unexpected introspection status code: {response.status_code}'
+            )
+            return False
+        token_information = response.json()
+        return 'active' in token_information \
+            and token_information['active']
+
+    def _validate_jwt(self, token: str, scopes: list) -> bool:
+        """ Validates a JWT token by first figuring out a matching
+        public key which must have been downloaded before (during
+        :func:`~flask_oauth2_validation.OAuth2Decorator.__init__` or
+        a configured update interval).
+
+        Second we hand over the token to the :mod:`jwt` module which decodes
+        it and performs basic validations.
+
+        Last we assert that the tokens audience matches the configured ones
+        and that all possibly expected scopes are present.
+        """
+        pubkey = None
+        if self._issuer_public_keys:
+            key_id = self._lookup_key_id(token)
+            if not key_id:
+                raise OAuth2BadRequestException(
+                    "No 'kid' attribute found in token header"
+                )
+            if key_id and key_id in self._issuer_public_keys:
+                pubkey = jwk_from_dict(self._issuer_public_keys[key_id])
+        if not pubkey:
+            raise OAuth2InvalidTokenException(
+                'Invalid token signature'
+            )
+        try:
+            decoded = self._jwt.decode(
+                token,
+                pubkey,
+                do_time_check=True
+            )
+            if 'iss' not in decoded or not self._issuer == decoded['iss']:
+                raise OAuth2InvalidTokenException(
+                    'Invalid token issuer'
+                )
+            if self._audience:
+                if ('aud' not in decoded
+                    or (type(self._audience) == dict
+                        and decoded['aud'] not in self._audience)
+                    or (type(self._audience) == str
+                        and not self._audience == decoded['aud'])):
+                    raise OAuth2InvalidTokenException(
+                        'Invalid token audience'
+                    )
+            if scopes and 'scp' not in decoded:
+                raise OAuth2InsufficientScopeException(
+                    ' '.join(sorted(set(scopes)))
+                )
+            if scopes and 'scp' in decoded:
+                decoded_scopes_set = set(decoded['scp'])
+                if scopes and not set(scopes).issubset(decoded_scopes_set):
+                    raise OAuth2InsufficientScopeException(
+                        ' '.join(
+                            sorted(set(scopes).difference(decoded_scopes_set))
+                        )
+                    )
+            self.token = decoded
+            return decoded
+        except JWTDecodeError as decode_error:
+            raise OAuth2InvalidTokenException(str(decode_error))
+
+    def _lookup_key_id(self, token: str) -> str:
+        """ Extracts the key id from the token header so that
+        we can match it against the ids of all known downloaded
+        public keys, later.
+        """
+        try:
+            header = token.split('.')[0]
+            # Correct the padding
+            header += '=' * (4 - len(header) % 4)
+            jwt_header = json.loads(base64.b64decode(header).decode('utf-8'))
+            if jwt_header and 'kid' in jwt_header:
+                return jwt_header['kid']
+        except BaseException:
+            raise OAuth2BadRequestException('Invalid token format')
+
+    def _update_keys(self):
+        """ Performs an automated update of our known authorization
+        server public keys based on the configured update interval.
+        """
+        if (self._jwks_update_interval
+                and self._jwks_last_update_timestamp):
+            # We only allow one update at a time to not mess up
+            # our list of pubkeys. This anyhow runs async to the
+            # requests so it shouldn't be recognizable by our
+            # clients.
+            with self._jwks_update_mutex:
+                now = time.time()
+                if int(self._jwks_last_update_timestamp) + \
+                        self._jwks_update_interval < now:
+                    self._jwks_last_update_timestamp = now
+                    try:
+                        self._lookup_keys()
+                    except TypeError as error:
+                        self._logger.error(error)
+
+    def requires_token(self, introspect=False, scopes=[]):
+        """ To provide OAuth2 token validation to your endpoints simply add the
+        :class:`~flask_oauth2_validation.OAuth2Decorator` like::
+
+            from flask_oauth2_validation import OAuth2Decorator
+
+            oauth2 = OAuth2Decorator(app)
+
+            @oauth2.requires_token()
+            @app.route('/protected')
+            def protected():
+                pass
+
+        This would perform local token validation, only. To enable remote token
+        validation you need to provide the introspect=True argument::
+
+            @oauth2.requires_token(introspect=True)
+            @app.route('/protected')
+            def protected():
+                pass
+
+        In case you require one or multiple scopes to allow execution, add the
+        `scopes=[...]` argument::
+
+            @oauth2.requires_token(scopes=['profile', 'email'])
+            @app.route('/protected')
+            def protected():
+                pass
+
+        To use the token from within your method you can access it via the
+        OAuth2Decorator object like::
+
+            @oauth2.requires_token()
+            @app.route('/protected')
+            def protected():
+                token: dict = oauth2.token
+                pass
+
+        :param introspect: feature toggle to turn on remote validation
+        :param scopes: optional list of mandatory scopes
+        """
+
+        def decorator(fn):
+            @wraps(fn)
+            def decorated(*args, **kwargs):
+                return self._handle_token(
+                    fn,
+                    *args,
+                    **dict(
+                        kwargs,
+                        scopes=scopes,
+                        introspect=introspect
+                    )
+                )
+            return decorated
+        return decorator
diff --git a/src/flask_oauth2_validation/exceptions.py b/src/flask_oauth2_validation/exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb1067600c58f980def9ed7624333eee2c749198
--- /dev/null
+++ b/src/flask_oauth2_validation/exceptions.py
@@ -0,0 +1,98 @@
+from flask import make_response
+
+
+class OAuth2Exception(BaseException):
+    """ Describes an HTTP error response which will be
+    returned back to the client in case of any validation
+    error.
+
+    The method `OAuth2Exception.response()` constructs
+    the Flask `flask.Response` object.
+
+    Error responses have an empty body. A `WWW-Authenticate`
+    response header will be set containing an error attribute
+    specifying the actual type of error. Each individual
+    `OAuth2Exception` subclass sets its own unique value.
+    Additional attributes may also be set containing further
+    error details.
+    """
+
+    def __init__(self, status_code: int, error: str, error_message: str):
+        """ Creates an `OAuth2Exception` object.
+        The `status_code` attributre defines the HTTP status code.
+        The `error` attribute defines the unique type of error.
+        And the `error_message` contains individual error details.
+        """
+        self.status_code = status_code
+        self.error = error
+        self.error_message = error_message
+
+    def response(self):
+        """ Assembles an `flask.Response` object including
+        a `WWW-Authenticate` header.
+        """
+
+        response = make_response()
+
+        # In case it has already been set we need to
+        # drop the Content-Type header as the response
+        # body will be empty.
+        response.headers.pop('Content-Type', None)
+
+        response.status_code = self.status_code
+        response.headers['WWW-Authenticate'] = ' '.join([
+            'Bearer',
+            'error="' + self.error + '"',
+            self._error_description()
+        ])
+        return response
+
+    def _error_description(self):
+        """ Creates a key-value pair to be added to the
+        `WWW-Authenticate` header which contains individual
+        error details.
+        """
+        return 'error_description="' + self.error_message + '"'
+
+
+class OAuth2BadRequestException(OAuth2Exception):
+    """ Describes an HTTP 400 (bad request) response:
+
+        `WWW-Authenticate: Bearer error="invalid_request" \
+                                  error_description="<msg>"`
+    """
+
+    def __init__(self, error_message: str):
+        super().__init__(400, 'invalid_request', error_message)
+
+
+class OAuth2InvalidTokenException(OAuth2Exception):
+    """ Describes an HTTP 401 (unauthorized) response:
+
+        `WWW-Authenticate: Bearer error="invalid_token" \
+                                  error_description="<msg>"`
+    """
+
+    def __init__(self, error_message: str):
+        super().__init__(401, 'invalid_token', error_message)
+
+
+class OAuth2InsufficientScopeException(OAuth2Exception):
+    """ Describes an HTTP 403 (forbidden) response. It contains
+    a whitespace separated list of scopes required but not granted:
+
+        `WWW-Authenticate: Bearer error="insufficient_scope" \
+                                  scope="<scope1> <scope2> ... <scopeN>"`
+    """
+
+    def __init__(self, missing_scope: str):
+        """ Creates an `OAuth2InsufficientScopeException` object.
+        The `status_code` attributre defines the HTTP status code.
+        The `error` attribute defines the unique type of error.
+        And the `missing_scope` is a list containing required but
+        not granted scopes.
+        """
+        super().__init__(403, 'insufficient_scope', missing_scope)
+
+    def _error_description(self):
+        return 'scope="' + self.error_message + '"'
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..541d78494e019792ed09ebd061ab1af3d2c34747
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,209 @@
+from flask import Flask
+import pytest
+import requests_mock
+
+from functional import test_jwk
+
+
+@pytest.fixture(scope='function')
+def test_app():
+    with requests_mock.Mocker() as mock:
+        _register_mock_addresses(mock)
+        yield _create_flask_app()
+
+
+def _create_flask_app():
+    app = Flask(__name__)
+    app.config['TESTING'] = True
+    return app
+
+
+def _register_mock_addresses(
+    mock: requests_mock.Mocker
+):
+
+    mock.get(
+        'https://unsupported.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        status_code=404
+    )
+
+    mock.get(
+        'https://missing_jwks.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'introspection_endpoint':
+                'https://issuer.local/oauth2/introspect',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_basic',
+                'client_secret_post'
+            ]
+        }
+    )
+
+    mock.get(
+        'https://missing_introspection.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_basic',
+                'client_secret_post'
+            ]
+        }
+    )
+
+    mock.get(
+        'https://missing_introspection_auth.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint':
+                'https://issuer.local/oauth2/introspect',
+        }
+    )
+
+    mock.get(
+        'https://issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint':
+                'https://issuer.local/oauth2/introspect',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_basic',
+                'client_secret_post'
+            ]
+        }
+    )
+
+    mock.get(
+        'https://basic_introspection.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint':
+                'https://basic_introspection.issuer.local/oauth2/introspect',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_basic'
+            ]
+        }
+    )
+
+    mock.get(
+        'https://issuer.local/oauth2/keys',
+        json={
+            'keys': [
+                {'kid': 'x'},
+                test_jwk,
+                {'kid': 'z'}
+            ]
+        }
+    )
+
+    mock.get(
+        'https://key_lookup_error.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://key_lookup_error.issuer.local/oauth2/keys',
+        }
+    )
+
+    mock.get(
+        'https://key_lookup_error.issuer.local/oauth2/keys',
+        status_code=500
+    )
+
+    mock.get(
+        'https://invalid_introspection.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint':
+                'https://invalid_introspection.issuer.local/oauth2/introspect',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_basic',
+                'client_secret_post'
+            ]
+        }
+    )
+
+    mock.post(
+        'https://invalid_introspection.issuer.local/oauth2/introspect',
+        json={
+            'active': False
+        }
+    )
+
+    mock.post(
+        'https://issuer.local/oauth2/introspect',
+        json={
+            'active': True
+        }
+    )
+
+    mock.post(
+        'https://basic_introspection.issuer.local/oauth2/introspect',
+        json={
+            'active': True
+        }
+    )
+
+    mock.get(
+        'https://introspection_error.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint':
+                'https://introspection_error.issuer.local/oauth2/introspect',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_basic',
+                'client_secret_post'
+            ]
+        }
+    )
+
+    mock.post(
+        'https://introspection_error.issuer.local/oauth2/introspect',
+        status_code=500
+    )
+
+    mock.get(
+        'https://unknown_auth.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://issuer.local/oauth2/keys',
+            'introspection_endpoint':
+                'https://unknown_auth.issuer.local/oauth2/introspect',
+            'introspection_endpoint_auth_methods_supported': [
+                'client_secret_unknown'
+            ]
+        }
+    )
+
+    mock.get(
+        'https://unknown_pubkey.issuer.local/oauth2' +
+        '/.well-known/oauth-authorization-server',
+        json={
+            'jwks_uri':
+                'https://unknown_pubkey.issuer.local/oauth2/keys',
+        }
+    )
+
+    mock.get(
+        'https://unknown_pubkey.issuer.local/oauth2/keys',
+        json={
+            'keys': [
+                {'kid': 'x'},
+                {'kid': 'z'}
+            ]
+        }
+    )
diff --git a/tests/functional/__init__.py b/tests/functional/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0679e2224cf0aadc5d8a9b0fc7bff02d48bac0d
--- /dev/null
+++ b/tests/functional/__init__.py
@@ -0,0 +1,45 @@
+from typing import Tuple
+from jwt.jwk import RSAJWK
+from cryptography.hazmat.primitives.asymmetric import rsa
+from jwt import JWT
+
+
+def _generate_test_keys() -> Tuple[rsa.RSAPublicKey, rsa.RSAPrivateKey]:
+    private_key: rsa.RSAPrivateKey = rsa.generate_private_key(
+        public_exponent=65537,
+        key_size=2048
+    )
+    public_key = private_key.public_key()
+    return public_key, private_key
+
+
+def _generate_test_jwk(public_key: rsa.RSAPublicKey) -> dict:
+    jwk = RSAJWK(public_key, kid='a', alg='RS256')
+    return jwk.to_dict(public_only=True)
+
+
+_public_key, _private_key = _generate_test_keys()
+_jwt = JWT()
+
+
+test_jwk = _generate_test_jwk(_public_key)
+
+
+def generate_test_token(
+    payload: dict,
+    optional_headers={'kid': 'a'},
+    key=RSAJWK(_private_key, kid='a', alg='RS256')
+) -> str:
+    return _jwt.encode(
+        payload=payload,
+        key=key,
+        alg='RS256',
+        optional_headers=optional_headers
+    )
+
+
+mocked_keys = {
+    'x': {'kid': 'x'},
+    'a': test_jwk,
+    'z': {'kid': 'z'}
+}
diff --git a/tests/functional/test_config.py b/tests/functional/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fc7270c0556275bbb7ba11aeadb13ec04a06aa0
--- /dev/null
+++ b/tests/functional/test_config.py
@@ -0,0 +1,127 @@
+from flask_oauth2_validation import OAuth2Decorator
+import pytest
+from . import mocked_keys
+
+
+def test_missing_config(test_app):
+    with pytest.raises(TypeError) as err:
+        OAuth2Decorator(test_app)
+    assert str(err.value) == 'An OAUTH2_ISSUER config property is required'
+
+
+def test_no_metadata_support(test_app):
+    with pytest.raises(TypeError) as err:
+        test_app.config['OAUTH2_ISSUER'] = \
+            'https://unsupported.issuer.local/oauth2'
+        OAuth2Decorator(test_app)
+    assert str(err.value) == \
+        'Cannot request authorization server metadata: 404'
+
+
+def test_missing_jwks_metadata(test_app):
+    with pytest.raises(TypeError) as err:
+        test_app.config['OAUTH2_ISSUER'] = \
+            'https://missing_jwks.issuer.local/oauth2'
+        OAuth2Decorator(test_app)
+    assert str(err.value) == \
+        'Cannot request authorization server metadata: ' + \
+        'No attribute jwks_uri found in authorization ' + \
+        'server metadata'
+
+
+def test_missing_introspection_metadata(test_app):
+    with pytest.raises(TypeError) as err:
+        test_app.config['OAUTH2_ISSUER'] = \
+            'https://missing_introspection.issuer.local/oauth2'
+        test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client'
+        test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure'
+        OAuth2Decorator(test_app)
+    assert str(err.value) == \
+        'Cannot request authorization server metadata: ' + \
+        'No attribute introspection_endpoint found in ' + \
+        'authorization server metadata'
+
+
+def test_missing_introspection_auth_metadata(test_app):
+    with pytest.raises(TypeError) as err:
+        test_app.config['OAUTH2_ISSUER'] = \
+            'https://missing_introspection_auth.issuer.local/oauth2'
+        test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client'
+        test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure'
+        OAuth2Decorator(test_app)
+    assert str(err.value) == \
+        'Cannot request authorization server metadata: ' + \
+        'No attribute introspection_endpoint_auth_methods_supported ' + \
+        'found in authorization server metadata'
+
+
+def test_local_validation(test_app):
+    test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2'
+    oauth2 = OAuth2Decorator(test_app)
+    assert oauth2._issuer == 'https://issuer.local/oauth2'
+    assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys'
+    assert oauth2._issuer_public_keys == mocked_keys
+    assert not oauth2._introspection_endpoint
+    assert not oauth2._introspection_auth_method
+    assert not oauth2._client_id
+    assert not oauth2._client_secret
+    assert not oauth2._jwks_update_interval
+    assert not oauth2._executor
+
+
+def test_local_validation_with_pubkey_reload(test_app):
+    test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2'
+    test_app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 1234
+    oauth2 = OAuth2Decorator(test_app)
+    assert oauth2._issuer == 'https://issuer.local/oauth2'
+    assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys'
+    assert oauth2._issuer_public_keys == mocked_keys
+    assert oauth2._jwks_update_interval == 1234
+    assert oauth2._executor
+    assert not oauth2._introspection_endpoint
+    assert not oauth2._introspection_auth_method
+    assert not oauth2._client_id
+    assert not oauth2._client_secret
+
+
+def test_remote_validation(test_app):
+    test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2'
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure'
+    oauth2 = OAuth2Decorator(test_app)
+    assert oauth2._issuer == 'https://issuer.local/oauth2'
+    assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys'
+    assert oauth2._issuer_public_keys == mocked_keys
+    assert oauth2._client_id == 'foo-client'
+    assert oauth2._client_secret == 'very-secure'
+    assert oauth2._introspection_endpoint == \
+        'https://issuer.local/oauth2/introspect'
+    assert oauth2._introspection_auth_method == 'client_secret_post'
+    assert not oauth2._jwks_update_interval
+    assert not oauth2._executor
+
+
+def test_remote_validation_with_pubkey_reload(test_app):
+    test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2'
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'very-secure'
+    test_app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 1234
+    oauth2 = OAuth2Decorator(test_app)
+    assert oauth2._issuer == 'https://issuer.local/oauth2'
+    assert oauth2._jwks_uri == 'https://issuer.local/oauth2/keys'
+    assert oauth2._issuer_public_keys == mocked_keys
+    assert oauth2._client_id == 'foo-client'
+    assert oauth2._client_secret == 'very-secure'
+    assert oauth2._introspection_endpoint == \
+        'https://issuer.local/oauth2/introspect'
+    assert oauth2._introspection_auth_method == 'client_secret_post'
+    assert oauth2._jwks_update_interval == 1234
+    assert oauth2._executor
+
+
+def test_introspection_setup_without_secret(test_app):
+    test_app.config['OAUTH2_ISSUER'] = 'https://issuer.local/oauth2'
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo-client'
+    with pytest.raises(TypeError) as err:
+        OAuth2Decorator(test_app)
+    assert str(err.value) == 'OAUTH2_CLIENT_SECRET config property required'
diff --git a/tests/functional/test_validation.py b/tests/functional/test_validation.py
new file mode 100644
index 0000000000000000000000000000000000000000..39f82173b7b8691f8014c5ec44a2d7336c680f06
--- /dev/null
+++ b/tests/functional/test_validation.py
@@ -0,0 +1,510 @@
+import pytest
+from flask import Flask, jsonify
+from flask_oauth2_validation import OAuth2Decorator
+from time import sleep
+from jwt.jwk import RSAJWK
+
+from . import generate_test_token, _generate_test_keys
+
+
+def _expect_requires_token(
+    app: Flask,
+    introspect=False,
+    scopes=[],
+    issuer='https://issuer.local/oauth2'
+):
+
+    app.config['OAUTH2_ISSUER'] = issuer
+
+    oauth2 = OAuth2Decorator(app)
+
+    @app.errorhandler(Exception)
+    def internal_server_error(e):
+        return jsonify({'error': str(e)}), 500
+
+    @app.route('/')
+    @oauth2.requires_token(
+        introspect=introspect,
+        scopes=scopes
+    )
+    def test_me():
+        return jsonify({
+            'token': oauth2.token
+        }), 200
+
+    @app.route('/raise')
+    @oauth2.requires_token(
+        introspect=introspect,
+        scopes=scopes
+    )
+    def raise_me():
+        raise Exception('Exception from decorated method')
+
+    @app.route('/fail')
+    @oauth2.requires_token(
+        introspect=introspect,
+        scopes=scopes
+    )
+    def fail_validation():
+        raise BaseException('Raised base exception')
+
+    return app.test_client()
+
+
+def _expect_valid_token(response):
+    assert 200 == response.status_code
+
+
+def _expect_internal_server_error(response, msg):
+    assert 500 == response.status_code
+    assert response.get_json()['error'] == 'Exception from decorated method'
+
+
+def _expect_insufficient_scope(response, scopes):
+
+    assert 403 == response.status_code
+
+    assert response.headers['WWW-Authenticate']
+    assert 'Bearer ' + \
+        'error="insufficient_scope" ' + \
+        'scope="'+scopes+'"' \
+        == response.headers['WWW-Authenticate']
+
+
+def _expect_invalid_token(response, msg):
+
+    assert 401 == response.status_code
+
+    assert response.headers['WWW-Authenticate']
+    assert 'Bearer ' + \
+        'error="invalid_token" ' + \
+        'error_description="'+msg+'"' \
+        == response.headers['WWW-Authenticate']
+
+
+def _expect_invalid_request(response, msg):
+
+    assert 400 == response.status_code
+
+    assert response.headers['WWW-Authenticate']
+    assert 'Bearer ' + \
+        'error="invalid_request" ' + \
+        'error_description="'+msg+'"' \
+        == response.headers['WWW-Authenticate']
+
+
+def test_request_without_headers(test_app):
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/')
+
+    _expect_invalid_request(response, 'Authorization header missing')
+
+
+def test_request_with_empty_authorization_header(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': ''
+    })
+
+    _expect_invalid_request(response, 'Authorization header missing')
+
+
+def test_request_missing_token(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer'
+    })
+
+    _expect_invalid_request(response, 'Bearer access token missing')
+
+
+def test_request_wrong_auth(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Basic asdfasdfasdf'
+    })
+
+    _expect_invalid_request(response, 'Bearer access token missing')
+
+
+def test_request_wrong_syntax(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer fooooobaaaar'
+    })
+
+    _expect_invalid_request(response, 'Invalid token format')
+
+
+def test_valid_token(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+        })
+    })
+
+    _expect_valid_token(response)
+
+
+def test_invalid_token_pubkey_lookup_error(test_app):
+
+    with pytest.raises(TypeError) as error:
+
+        _expect_requires_token(
+            test_app,
+            issuer='https://key_lookup_error.issuer.local/oauth2'
+        )
+
+        assert str(error.value) ==  \
+            'Cannot request public keys from ' + \
+            'https: // key_lookup_error.issuer.local/oauth2/keys'
+
+
+def test_invalid_token_header_kid_missing(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token(
+            {
+                'iss': 'https://issuer.local/oauth2'
+            },
+            optional_headers={}
+        )
+    })
+
+    _expect_invalid_request(
+        response, "No 'kid' attribute found in token header"
+    )
+
+
+def test_invalid_token_corrupt_Header(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' +
+        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ.' +
+        'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI' +
+        '6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.' +
+        'SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
+
+    })
+
+    _expect_invalid_request(
+        response, 'Invalid token format'
+    )
+
+
+def test_invalid_audience(test_app: Flask):
+
+    test_app.config['OAUTH2_AUDIENCE'] = 'api://default'
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+            'aud': 'non-matching-audience',
+        })
+    })
+
+    _expect_invalid_token(response, 'Invalid token audience')
+
+
+def test_valid_audience(test_app: Flask):
+
+    test_app.config['OAUTH2_AUDIENCE'] = 'api://default'
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+            'aud': 'api://default',
+        })
+    })
+
+    _expect_valid_token(response)
+
+
+def test_invalid_issuer(test_app: Flask):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'other-issuer',
+        })
+    })
+
+    _expect_invalid_token(response, 'Invalid token issuer')
+
+
+def test_valid_token_with_scopes(test_app):
+
+    test_client = _expect_requires_token(test_app, scopes=['foo', 'bar'])
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+            'scp': ['foo', 'bar']
+        })
+    })
+
+    _expect_valid_token(response)
+
+
+def test_valid_token_missing_scope(test_app):
+
+    test_client = _expect_requires_token(test_app, scopes=['foo', 'bar'])
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+            'scp': ['foo']
+        })
+    })
+
+    _expect_insufficient_scope(response, 'bar')
+
+
+def test_valid_token_no_scopes(test_app):
+
+    test_client = _expect_requires_token(test_app, scopes=['foo', 'bar'])
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+        })
+    })
+
+    _expect_insufficient_scope(response, 'bar foo')
+
+
+def test_valid_token_introspected_post(test_app):
+
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar'
+
+    test_client = _expect_requires_token(
+        test_app,
+        introspect=True
+    )
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+        })
+    })
+
+    _expect_valid_token(response)
+
+
+def test_valid_token_introspected_basic(test_app):
+
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar'
+
+    test_client = _expect_requires_token(
+        test_app,
+        introspect=True,
+        issuer='https://basic_introspection.issuer.local/oauth2'
+    )
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://basic_introspection.issuer.local/oauth2',
+        })
+    })
+
+    _expect_valid_token(response)
+
+
+def test_valid_token_introspected_unknown_auth(test_app):
+
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar'
+
+    with pytest.raises(TypeError) as error:
+
+        _expect_requires_token(
+            test_app,
+            introspect=True,
+            issuer='https://unknown_auth.issuer.local/oauth2'
+        )
+
+        assert str(error.value) == \
+            'The introspection auth methods are not supported: ' + \
+            'client_secret_unknown'
+
+
+def test_invalid_token_introspection_error(test_app):
+
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar'
+
+    test_client = _expect_requires_token(
+        test_app,
+        introspect=True,
+        issuer='https://introspection_error.issuer.local/oauth2'
+    )
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://introspection_error.issuer.local/oauth2',
+        })
+    })
+
+    _expect_invalid_token(response, 'Invalid token')
+
+
+def test_invalid_token_introspected(test_app):
+
+    test_app.config['OAUTH2_CLIENT_ID'] = 'foo'
+    test_app.config['OAUTH2_CLIENT_SECRET'] = 'bar'
+
+    test_client = _expect_requires_token(
+        test_app,
+        introspect=True,
+        issuer='https://invalid_introspection.issuer.local/oauth2'
+    )
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://invalid_introspection.issuer.local/oauth2',
+        })
+    })
+
+    _expect_invalid_token(response, 'Invalid token')
+
+
+def test_introspect_config_missing(test_app):
+
+    test_client = _expect_requires_token(
+        test_app,
+        introspect=True
+    )
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+        })
+    })
+
+    _expect_invalid_token(response, 'Invalid configuration')
+
+
+def test_expired_token(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+            'iat': 1,
+            'exp': 2
+        })
+    })
+
+    _expect_invalid_token(response, 'JWT Expired')
+
+
+def test_invalid_token_unknown_pubkey(test_app):
+
+    test_client = _expect_requires_token(
+        test_app,
+        issuer='https://unknown_pubkey.issuer.local/oauth2'
+    )
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://unknown_pubkey.issuer.local/oauth2'
+        })
+    })
+
+    _expect_invalid_token(response, 'Invalid token signature')
+
+
+def test_decorated_method_raises_exception(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/raise', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2'
+        })
+    })
+
+    _expect_internal_server_error(response, 'Exception from decorated method')
+
+
+def test_decorated_method_raises_base_exception(test_app):
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/fail', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2'
+        })
+    })
+
+    _expect_invalid_token(response, 'Token validation failed')
+
+
+def test_valid_token_with_pubkey_refresh(test_app):
+
+    test_app.config['OAUTH2_JWKS_UPDATE_INTERVAL'] = 1
+
+    test_client = _expect_requires_token(test_app)
+
+    first_response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+        })
+    })
+
+    _expect_valid_token(first_response)
+
+    sleep(1.1)
+
+    second_response_caused_pubkey_reload = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token({
+            'iss': 'https://issuer.local/oauth2',
+        })
+    })
+
+    _expect_valid_token(second_response_caused_pubkey_reload)
+
+    # Wait for the async key update to finish
+    sleep(0.1)
+
+
+def test_invalid_token_wrong_pubkey(test_app):
+
+    _, priv = _generate_test_keys()
+
+    test_client = _expect_requires_token(test_app)
+
+    response = test_client.get('/', headers={
+        'Authorization': 'Bearer ' + generate_test_token(
+            {
+                'iss': 'https://issuer.local/oauth2',
+            },
+            key=RSAJWK(priv, kid='a', alg='RS256')
+        )
+    })
+
+    _expect_invalid_token(response, 'failed to decode JWT')