File size: 26,487 Bytes
d086025
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
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
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
--- /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
--- /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
--- /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
--- /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')