servlet-oauth2-resource-server-jwt.md 40.6 KB
Newer Older
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 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
# OAuth2.0资源服务器JWT

## JWT的最小依赖项

大多数资源服务器支持被收集到`spring-security-oauth2-resource-server`中。然而,对JWTS的解码和验证的支持是`spring-security-oauth2-jose`,这意味着这两个都是必要的,以便拥有一个支持JWT编码的承载令牌的工作资源服务器。

## JWTS的最小配置

当使用[Spring Boot](https://spring.io/projects/spring-boot)时,将应用程序配置为资源服务器包括两个基本步骤。首先,包括所需的依赖关系,其次,指示授权服务器的位置。

### 指定授权服务器

在 Spring 引导应用程序中,要指定使用哪个授权服务器,只需执行以下操作:

```
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://idp.example.com/issuer
```

其中`[https://idp.example.com/issuer](https://idp.example.com/issuer)`是授权服务器将发布的JWT令牌的`iss`声明中包含的值。Resource Server将使用此属性进一步自我配置,发现授权服务器的公钥,并随后验证传入的JWTS。

|   |要使用`issuer-uri`属性,还必须证明`[https://idp.example.com/issuer/.well-known/openid-configuration](https://idp.example.com/issuer/.well-known/openid-configuration)``[https://idp.example.com/.well-known/openid-configuration/issuer](https://idp.example.com/.well-known/openid-configuration/issuer)``[https://idp.example.com/.well-known/oauth-authorization-server/issuer](https://idp.example.com/.well-known/oauth-authorization-server/issuer)`中的一个是授权服务器所支持的端点。<br/>此端点被称为[提供者配置](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig)端点或[授权服务器元数据](https://tools.ietf.org/html/rfc8414#section-3)端点。|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

就这样!

### 创业期望

当使用此属性和这些依赖项时,Resource Server将自动配置自身以验证JWT编码的承载令牌。

它通过一个确定性的启动过程来实现这一点:

1. 查询`jwks_url`属性的提供者配置或授权服务器元数据端点

2. 查询`jwks_url`端点以获得支持的算法

3. 将验证策略配置为查询`jwks_url`中找到的算法的有效公钥

4. 将验证策略配置为针对`[https://idp.example.com](https://idp.example.com)`的每个JWTS`iss`索赔进行验证。

此过程的结果是,为了使资源服务器成功启动,授权服务器必须启动并接收请求。

|   |如果在资源服务器查询时,授权服务器处于关闭状态(给定适当的超时),那么启动将失败。|
|---|-------------------------------------------------------------------------------------------------------------------------|

### 运行时期望

一旦启动应用程序,Resource Server将尝试处理任何包含`Authorization: Bearer`报头的请求:

```
GET / HTTP/1.1
Authorization: Bearer some-token-value # Resource Server will process this
```

只要表明了该方案,资源服务器就会尝试根据承载令牌规范来处理请求。

给定一个格式良好的JWT,资源服务器将:

1. 根据在启动过程中从`jwks_url`端点获得并与JWT匹配的公钥验证其签名

2. 验证JWT的`exp``nbf`时间戳以及JWT的`iss`声明,并

3. 将每个作用域映射到一个前缀`SCOPE_`的权限。

|   |由于授权服务器提供了可用的新密钥, Spring 安全性将自动旋转用于验证JWTS的密钥。|
|---|-------------------------------------------------------------------------------------------------------------------------------|

默认情况下,生成的`Authentication#getPrincipal`是 Spring security`Jwt`对象,并且`Authentication#getName`映射到JWT的`sub`属性(如果存在)。

从这里开始,考虑跳到:

* [JWT身份验证的工作方式](#oauth2resourceserver-jwt-architecture)

* [如何在不将资源服务器启动与授权服务器的可用性绑定的情况下进行配置](#oauth2resourceserver-jwt-jwkseturi)

* [How to Configure without Spring Boot](#oauth2resourceserver-jwt-sansboot)

## JWT身份验证的工作方式

接下来,让我们看看 Spring Security在基于 Servlet 的应用程序中支持[JWT](https://tools.ietf.org/html/rfc7519)身份验证所使用的体系结构组件,就像我们刚才看到的那样。

[`JwtAuthenticationProvider`](https://DOCS. Spring.io/ Spring-security/site/DOCS/5.6.2/api/org/springframework/security/oauth2/server/resource/authentication/jwtauthenticationprovider.html)是一个[`AuthenticationProvider`](../.../././////认证/architectification/architecture.html# Servlet-authentification-authenticationprovider)实现,它利用了一个[<`JwtDecoder`](#oaut

让我们来看看`JwtAuthenticationProvider`在 Spring 安全性中是如何工作的。该图详细说明了`AuthenticationManager`](.../../authentication/architecture.html# Servlet-authentication-authenticationmanager)在[读取不记名令牌](#oauth2resourceserver-authentication-bearertokenauthenticationfilter)中的工作原理。

![JWTAutHenticationProvider](https://docs.spring.io/spring-security/reference/_images/servlet/oauth2/jwtauthenticationprovider.png)

图1. `JwtAuthenticationProvider`用法

![number 1](https://docs.spring.io/spring-security/reference/_images/icons/number_1.png)来自[读取不记名令牌](#oauth2resourceserver-authentication-bearertokenauthenticationfilter)的身份验证`Filter`将一个`BearerTokenAuthenticationToken`传递到`AuthenticationManager`,这是由[`ProviderManager`](.../../authentication/architecture.html# Servlet-authentication-providermanager)实现的。

![number 2](https://docs.spring.io/spring-security/reference/_images/icons/number_2.png)`ProviderManager`被配置为使用[身份验证提供者](../../authentication/architecture.html#servlet-authentication-authenticationprovider)类型的`JwtAuthenticationProvider`

![number 3](https://docs.spring.io/spring-security/reference/_images/icons/number_3.png)`JwtAuthenticationProvider`使用[`JwtDecoder`](#OAuth2Resourceserver-JWT-decoder)对`Jwt`进行解码、验证和验证。

![number 4](https://docs.spring.io/spring-security/reference/_images/icons/number_4.png)`JwtAuthenticationProvider`然后使用[`JwtAuthenticationConverter`](#OAuth2Resourceserver-JWT-Authorization-Extraction)将`Jwt`转换为授予权限的`Collection`

![number 5](https://docs.spring.io/spring-security/reference/_images/icons/number_5.png)当身份验证成功时,返回的[`Authentication`](.../../authentication/architecture.html# Servlet-authentication-authentication)类型为`JwtAuthenticationToken`,并且具有一个主体,即由配置的`JwtDecoder`返回的`Jwt`。最终,返回的`JwtAuthenticationToken`将由身份验证`Filter`设置在[`SecurityContextHolder`](.../authentication/architecture.html# Servlet-authentication-securitycontextholder)上。

## 直接指定授权服务器JWK设置的URI

如果授权服务器不支持任何配置端点,或者如果资源服务器必须能够独立于授权服务器启动,那么也可以提供`jwk-set-uri`:

```
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://idp.example.com
          jwk-set-uri: https://idp.example.com/.well-known/jwks.json
```

|   |JWK集URI不是标准化的,但通常可以在授权服务器的文档中找到。|
|---|-----------------------------------------------------------------------------------------------------------|

因此,资源服务器不会在启动时对授权服务器进行ping。我们仍然指定`issuer-uri`,以便Resource Server仍然在传入的JWTS上验证`iss`声明。

|   |也可以在[DSL](#oauth2resourceserver-jwt-jwkseturi-dsl)上直接提供此属性。|
|---|--------------------------------------------------------------------------------------------------|

## 覆盖或替换Boot Auto配置

有两个`@Bean`s, Spring boot代表资源服务器生成。

第一个是将应用程序配置为资源服务器的`WebSecurityConfigurerAdapter`。当包含`spring-security-oauth2-jose`时,这个`WebSecurityConfigurerAdapter`看起来是这样的:

例1.默认的JWT配置

Java

```
protected void configure(HttpSecurity http) {
    http
        .authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
}
```

Kotlin

```
fun configure(http: HttpSecurity) {
    http {
        authorizeRequests {
            authorize(anyRequest, authenticated)
        }
        oauth2ResourceServer {
            jwt { }
        }
    }
}
```

如果应用程序不公开`WebSecurityConfigurerAdapter` Bean,那么 Spring 引导将公开上面的默认引导。

替换它就像在应用程序中公开 Bean 一样简单:

例2.自定义JWT配置

Java

```
@EnableWebSecurity
public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeHttpRequests(authorize -> authorize
                .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(myConverter())
                )
            );
    }
}
```

Kotlin

```
@EnableWebSecurity
class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize("/messages/**", hasAuthority("SCOPE_message:read"))
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt {
                    jwtAuthenticationConverter = myConverter()
                }
            }
        }
    }
}
```

对于任何以`/messages/`开头的URL,上面要求`message:read`的范围。

`oauth2ResourceServer`DSL上的方法也将覆盖或替换自动配置。

例如,第二个`@Bean` Spring 引导创建了一个`JwtDecoder`,它[将`String`令牌解码为`Jwt`的验证实例](#OAuth2Resourceserver-jwt-architecture-jwtdecoder):

例3. JWT解码器

Java

```
@Bean
public JwtDecoder jwtDecoder() {
    return JwtDecoders.fromIssuerLocation(issuerUri);
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return JwtDecoders.fromIssuerLocation(issuerUri)
}
```

|   |调用`[JwtDecoders#fromIssuerLocation](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/jwt/JwtDecoders.html#fromIssuerLocation-java.lang.String-)`是调用提供程序配置或授权服务器元数据端点以派生JWK集URI的目的。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

如果应用程序不公开`JwtDecoder` Bean,那么 Spring 引导将公开上面的默认引导。

并且其配置可以使用`jwkSetUri()`重写或使用`decoder()`替换。

或者,如果根本不使用 Spring boot,那么这两个组件--过滤器链和`JwtDecoder`都可以用XML指定。

过滤链是这样指定的:

例4.默认的JWT配置

XML

```
<http>
    <intercept-uri pattern="/**" access="authenticated"/>
    <oauth2-resource-server>
        <jwt decoder-ref="jwtDecoder"/>
    </oauth2-resource-server>
</http>
```

`JwtDecoder`就像这样:

例5. JWT解码器

XML

```
<bean id="jwtDecoder"
        class="org.springframework.security.oauth2.jwt.JwtDecoders"
        factory-method="fromIssuerLocation">
    <constructor-arg value="${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}"/>
</bean>
```

### `

可以配置授权服务器的JWK集URI[作为配置属性](#oauth2resourceserver-jwt-jwkseturi),也可以在DSL中提供它:

例6. JWK设置URI配置

Java

```
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
                )
            );
    }
}
```

Kotlin

```
@EnableWebSecurity
class DirectlyConfiguredJwkSetUri : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt {
                    jwkSetUri = "https://idp.example.com/.well-known/jwks.json"
                }
            }
        }
    }
}
```

XML

```
<http>
    <intercept-uri pattern="/**" access="authenticated"/>
    <oauth2-resource-server>
        <jwt jwk-set-uri="https://idp.example.com/.well-known/jwks.json"/>
    </oauth2-resource-server>
</http>
```

使用`jwkSetUri()`优先于任何配置属性。

### `

`jwkSetUri()`更强大的是`decoder()`,它将完全取代[`JwtDecoder`](#OAuth2Resourceserver-jwt-architecture-jwtdecoder)的任何引导自动配置:

例7. JWT解码器配置

Java

```
@EnableWebSecurity
public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .decoder(myCustomDecoder())
                )
            );
    }
}
```

Kotlin

```
@EnableWebSecurity
class DirectlyConfiguredJwtDecoder : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt {
                    jwtDecoder = myCustomDecoder()
                }
            }
        }
    }
}
```

XML

```
<http>
    <intercept-uri pattern="/**" access="authenticated"/>
    <oauth2-resource-server>
        <jwt decoder-ref="myCustomDecoder"/>
    </oauth2-resource-server>
</http>
```

当需要更深的配置时,比如[validation](#oauth2resourceserver-jwt-validation)[mapping](#oauth2resourceserver-jwt-claimsetmapping)[请求超时](#oauth2resourceserver-jwt-timeouts),这是很方便的。

### 曝光`JwtDecoder``@Bean`

或者,暴露[`JwtDecoder`](#OAuth2Resourceserver-JWT-Architecture-JWTDecoder)`@Bean`具有与`decoder()`相同的效果:

Java

```
@Bean
public JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
}
```

## 配置可信算法

默认情况下,`NimbusJwtDecoder`以及资源服务器将仅使用`RS256`信任和验证令牌。

你可以通过[Spring Boot](#oauth2resourceserver-jwt-boot-algorithm)[NimbusJWTDecoder Builder](#oauth2resourceserver-jwt-decoder-builder)或从[JWK SET响应](#oauth2resourceserver-jwt-decoder-jwk-response)进行自定义。

### 通过 Spring 引导

设置算法的最简单方法是作为一个属性:

```
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          jws-algorithm: RS512
          jwk-set-uri: https://idp.example.org/.well-known/jwks.json
```

### 使用构建器

不过,要获得更大的功率,我们可以使用带有`NimbusJwtDecoder`的建造器:

Java

```
@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
            .jwsAlgorithm(RS512).build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
            .jwsAlgorithm(RS512).build()
}
```

多次调用`jwsAlgorithm`将配置`NimbusJwtDecoder`来信任多个算法,如下所示:

Java

```
@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
            .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
            .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
}
```

或者,你可以调用`jwsAlgorithms`:

Java

```
@Bean
JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
            .jwsAlgorithms(algorithms -> {
                    algorithms.add(RS512);
                    algorithms.add(ES512);
            }).build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
            .jwsAlgorithms {
                it.add(RS512)
                it.add(ES512)
            }.build()
}
```

### 来自JWK SET响应

Spring 由于Security的JWT支持是基于Nimbus的,所以你也可以使用它的所有优秀功能。

例如,Nimbus有一个`JWSKeySelector`实现,该实现将基于JWK设置的URI响应来选择一组算法。你可以使用它生成`NimbusJwtDecoder`,如下所示:

Java

```
@Bean
public JwtDecoder jwtDecoder() {
    // makes a request to the JWK Set endpoint
    JWSKeySelector<SecurityContext> jwsKeySelector =
            JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl);

    DefaultJWTProcessor<SecurityContext> jwtProcessor =
            new DefaultJWTProcessor<>();
    jwtProcessor.setJWSKeySelector(jwsKeySelector);

    return new NimbusJwtDecoder(jwtProcessor);
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    // makes a request to the JWK Set endpoint
    val jwsKeySelector: JWSKeySelector<SecurityContext> = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL<SecurityContext>(this.jwkSetUrl)
    val jwtProcessor: DefaultJWTProcessor<SecurityContext> = DefaultJWTProcessor()
    jwtProcessor.jwsKeySelector = jwsKeySelector
    return NimbusJwtDecoder(jwtProcessor)
}
```

## 信任单一的非对称密钥

比支持具有JWK设置端点的资源服务器更简单的方法是对RSA公钥进行硬编码。公钥可以通过[Spring Boot](#oauth2resourceserver-jwt-decoder-public-key-boot)[使用构建器](#oauth2resourceserver-jwt-decoder-public-key-builder)提供。

### 通过 Spring 引导

通过 Spring 引导指定一个键非常简单。密钥的位置可以这样指定:

```
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          public-key-location: classpath:my-key.pub
```

或者,为了允许更复杂的查找,你可以对`RsaKeyConversionServicePostProcessor`进行后处理:

Java

```
@Bean
BeanFactoryPostProcessor conversionServiceCustomizer() {
    return beanFactory ->
        beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
                .setResourceLoader(new CustomResourceLoader());
}
```

Kotlin

```
@Bean
fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
    return BeanFactoryPostProcessor { beanFactory ->
        beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
                .setResourceLoader(CustomResourceLoader())
    }
}
```

指定你的密钥的位置:

```
key.location: hfds://my-key.pub
```

然后自动连接该值:

Java

```
@Value("${key.location}")
RSAPublicKey key;
```

Kotlin

```
@Value("\${key.location}")
val key: RSAPublicKey? = null
```

### 使用构建器

要直接连接`RSAPublicKey`,只需使用适当的`NimbusJwtDecoder`构建器,如下所示:

Java

```
@Bean
public JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withPublicKey(this.key).build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withPublicKey(this.key).build()
}
```

## 信任单一的对称密钥

使用单一的对称密钥也很简单。你可以简单地在`SecretKey`中加载,并使用适当的`NimbusJwtDecoder`构建器,如下所示:

Java

```
@Bean
public JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withSecretKey(this.key).build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    return NimbusJwtDecoder.withSecretKey(key).build()
}
```

## 配置授权

从OAuth2.0授权服务器发出的JWT通常具有`scope``scp`属性,指示已授予的范围(或权限),例如:

`{ …​, "scope" : "messages contacts"}`

在这种情况下,Resource Server将尝试强制将这些作用域放入一个已授予权限的列表中,并在每个作用域前加上字符串“scope\_”。

这意味着,要使用从JWT派生的作用域来保护端点或方法,相应的表达式应该包括以下前缀:

例8.授权配置

Java

```
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeHttpRequests(authorize -> authorize
                .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
                .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    }
}
```

Kotlin

```
@EnableWebSecurity
class DirectlyConfiguredJwkSetUri : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
        http {
            authorizeRequests {
                authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
                authorize("/messages/**", hasAuthority("SCOPE_messages"))
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt { }
            }
        }
    }
}
```

XML

```
<http>
    <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
    <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
    <oauth2-resource-server>
        <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"/>
    </oauth2-resource-server>
</http>
```

或类似于方法安全性:

Java

```
@PreAuthorize("hasAuthority('SCOPE_messages')")
public List<Message> getMessages(...) {}
```

Kotlin

```
@PreAuthorize("hasAuthority('SCOPE_messages')")
fun getMessages(): List<Message> { }
```

### 手动提取权限

然而,在许多情况下,这种默认设置是不够的。例如,一些授权服务器不使用`scope`属性,而是具有自己的自定义属性。或者,在其他时候,资源服务器可能需要将属性或属性的组合调整为内在化的权限。

为此, Spring Security附带`JwtAuthenticationConverter`,它负责[将`Jwt`转换为`Authentication`](#OAuth2Resourceserver-JWT-Architecture-JWTAutoThenticationConverter)。默认情况下, Spring 安全性将用`JwtAuthenticationProvider`的默认实例连接`JwtAuthenticationConverter`

作为配置`JwtAuthenticationConverter`的一部分,你可以提供一个附属转换器,将其从`Jwt`转换为授予权限的`Collection`

假设你的授权服务器在一个名为`authorities`的自定义声明中与权威机构通信。在这种情况下,你可以配置[`JwtAuthenticationConverter`](#OAuth2ResourceServer-JWT-Architecture-JWTAutoThenticationConverter)应该检查的声明,如下所示:

例9.当局声称配置

Java

```
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
    grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");

    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
    return jwtAuthenticationConverter;
}
```

Kotlin

```
@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
    val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
    grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities")

    val jwtAuthenticationConverter = JwtAuthenticationConverter()
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
    return jwtAuthenticationConverter
}
```

XML

```
<http>
    <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
    <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
    <oauth2-resource-server>
        <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
                jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
    </oauth2-resource-server>
</http>

<bean id="jwtAuthenticationConverter"
        class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
    <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
</bean>

<bean id="jwtGrantedAuthoritiesConverter"
        class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
    <property name="authoritiesClaimName" value="authorities"/>
</bean>
```

你也可以将权限前缀配置为不同的。你可以将它更改为`ROLE_`,而不是在每个权限前加上`SCOPE_`,就像这样:

例10.权限前缀配置

Java

```
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
    grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");

    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
    return jwtAuthenticationConverter;
}
```

Kotlin

```
@Bean
fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
    val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
    grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_")

    val jwtAuthenticationConverter = JwtAuthenticationConverter()
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
    return jwtAuthenticationConverter
}
```

XML

```
<http>
    <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
    <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
    <oauth2-resource-server>
        <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
                jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
    </oauth2-resource-server>
</http>

<bean id="jwtAuthenticationConverter"
        class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
    <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
</bean>

<bean id="jwtGrantedAuthoritiesConverter"
        class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
    <property name="authorityPrefix" value="ROLE_"/>
</bean>
```

或者,你可以通过调用`JwtGrantedAuthoritiesConverter#setAuthorityPrefix("")`来完全删除前缀。

为了具有更大的灵活性,DSL支持用实现`Converter<Jwt, AbstractAuthenticationToken>`的任何类完全替换转换器:

Java

```
static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
    public AbstractAuthenticationToken convert(Jwt jwt) {
        return new CustomAuthenticationToken(jwt);
    }
}

// ...

@EnableWebSecurity
public class CustomAuthenticationConverterConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(new CustomAuthenticationConverter())
                )
            );
    }
}
```

Kotlin

```
internal class CustomAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
    override fun convert(jwt: Jwt): AbstractAuthenticationToken {
        return CustomAuthenticationToken(jwt)
    }
}

// ...

@EnableWebSecurity
class CustomAuthenticationConverterConfig : WebSecurityConfigurerAdapter() {
    override fun configure(http: HttpSecurity) {
       http {
            authorizeRequests {
                authorize(anyRequest, authenticated)
            }
           oauth2ResourceServer {
               jwt {
                   jwtAuthenticationConverter = CustomAuthenticationConverter()
               }
           }
        }
    }
}
```

## 配置验证

使用[minimal Spring Boot configuration](#oauth2resourceserver-jwt-minimalconfiguration)(表示授权服务器的发行者URI),Resource Server将默认验证`iss`声明以及`exp``nbf`时间戳声明。

在需要定制验证的情况下,Resource Server附带两个标准验证器,并且还接受定制的`OAuth2TokenValidator`实例。

### 自定义时间戳验证

JWT通常有一个有效窗口,窗口的开始在`nbf`索赔中指示,结束在`exp`索赔中指示。

然而,每个服务器都可能经历时钟漂移,这可能导致令牌在一台服务器上出现过期,而不是在另一台服务器上出现。随着分布式系统中协作服务器数量的增加,这可能会导致一些实现令人心烦。

Resource Server使用`JwtTimestampValidator`来验证令牌的有效性窗口,并且可以将其配置为`clockSkew`以缓解上述问题:

Java

```
@Bean
JwtDecoder jwtDecoder() {
     NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
             JwtDecoders.fromIssuerLocation(issuerUri);

     OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
            new JwtTimestampValidator(Duration.ofSeconds(60)),
            new JwtIssuerValidator(issuerUri));

     jwtDecoder.setJwtValidator(withClockSkew);

     return jwtDecoder;
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder

    val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
            JwtTimestampValidator(Duration.ofSeconds(60)),
            JwtIssuerValidator(issuerUri))

    jwtDecoder.setJwtValidator(withClockSkew)

    return jwtDecoder
}
```

|   |默认情况下,Resource Server配置的时钟偏差为60秒。|
|---|------------------------------------------------------------------|

### 配置自定义验证器

使用`OAuth2TokenValidator`API添加`aud`声明的检查很简单:

Java

```
OAuth2TokenValidator<Jwt> audienceValidator() {
    return new JwtClaimValidator<List<String>>(AUD, aud -> aud.contains("messaging"));
}
```

Kotlin

```
fun audienceValidator(): OAuth2TokenValidator<Jwt?> {
    return JwtClaimValidator<List<String>>(AUD) { aud -> aud.contains("messaging") }
}
```

或者,为了获得更多的控制,你可以实现自己的`OAuth2TokenValidator`:

Java

```
static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
    OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);

    @Override
    public OAuth2TokenValidatorResult validate(Jwt jwt) {
        if (jwt.getAudience().contains("messaging")) {
            return OAuth2TokenValidatorResult.success();
        } else {
            return OAuth2TokenValidatorResult.failure(error);
        }
    }
}

// ...

OAuth2TokenValidator<Jwt> audienceValidator() {
    return new AudienceValidator();
}
```

Kotlin

```
internal class AudienceValidator : OAuth2TokenValidator<Jwt> {
    var error: OAuth2Error = OAuth2Error("custom_code", "Custom error message", null)

    override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
        return if (jwt.audience.contains("messaging")) {
            OAuth2TokenValidatorResult.success()
        } else {
            OAuth2TokenValidatorResult.failure(error)
        }
    }
}

// ...

fun audienceValidator(): OAuth2TokenValidator<Jwt> {
    return AudienceValidator()
}
```

然后,要添加到资源服务器中,需要指定[`JwtDecoder`](#OAuth2Resourceserver-jwt-architecture-jwtdecoder)实例:

Java

```
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
        JwtDecoders.fromIssuerLocation(issuerUri);

    OAuth2TokenValidator<Jwt> audienceValidator = audienceValidator();
    OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
    OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);

    jwtDecoder.setJwtValidator(withAudience);

    return jwtDecoder;
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder

    val audienceValidator = audienceValidator()
    val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
    val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)

    jwtDecoder.setJwtValidator(withAudience)

    return jwtDecoder
}
```

## 配置索赔集映射

Spring 安全性使用[Nimbus](https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home)库来解析JWTS并验证其签名。因此, Spring 安全性取决于Nimbus对每个字段值的解释以及如何将每个字段值强制为 Java 类型。

例如,因为Nimbus保持 Java 7兼容,所以它不使用`Instant`来表示时间戳字段。

而且完全有可能使用不同的库或用于JWT处理,这可能会做出自己的强制决策,需要进行调整。

或者,非常简单地说,出于特定于域的原因,资源服务器可能希望从JWT中添加或删除声明。

出于这些目的,Resource Server支持用`MappedJwtClaimSetConverter`映射JWT索赔集。

### 定制单个索赔的转换

默认情况下,`MappedJwtClaimSetConverter`将尝试强制将声明转换为以下类型:

|Claim|Java 类型|
|-----|--------------------|
|`aud`|`Collection<String>`|
|`exp`|`Instant`|
|`iat`|`Instant`|
|`iss`|`String`|
|`jti`|`String`|
|`nbf`|`Instant`|
|`sub`|`String`|

可以使用`MappedJwtClaimSetConverter.withDefaults`配置单个索赔的转换策略:

Java

```
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();

    MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
            .withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));
    jwtDecoder.setClaimSetConverter(converter);

    return jwtDecoder;
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    val jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()

    val converter = MappedJwtClaimSetConverter
            .withDefaults(mapOf("sub" to this::lookupUserIdBySub))
    jwtDecoder.setClaimSetConverter(converter)

    return jwtDecoder
}
```

这将保留所有的默认值,除了它将覆盖`sub`的默认索赔转换器。

### 增加索赔

`MappedJwtClaimSetConverter`还可以用于添加自定义声明,例如,用于适应现有系统:

Java

```
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
```

Kotlin

```
MappedJwtClaimSetConverter.withDefaults(mapOf("custom" to Converter<Any, String> { "value" }))
```

### 删除索赔

删除声明也很简单,使用相同的API:

Java

```
MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
```

Kotlin

```
MappedJwtClaimSetConverter.withDefaults(mapOf("legacyclaim" to Converter<Any, Any> { null }))
```

### 重新命名索赔

在更复杂的场景中,例如一次查询多个声明或重命名一个声明,Resource Server接受实现`Converter<Map<String, Object>, Map<String,Object>>`的任何类:

Java

```
public class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {
    private final MappedJwtClaimSetConverter delegate =
            MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());

    public Map<String, Object> convert(Map<String, Object> claims) {
        Map<String, Object> convertedClaims = this.delegate.convert(claims);

        String username = (String) convertedClaims.get("user_name");
        convertedClaims.put("sub", username);

        return convertedClaims;
    }
}
```

Kotlin

```
class UsernameSubClaimAdapter : Converter<Map<String, Any?>, Map<String, Any?>> {
    private val delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap())
    override fun convert(claims: Map<String, Any?>): Map<String, Any?> {
        val convertedClaims = delegate.convert(claims)
        val username = convertedClaims["user_name"] as String
        convertedClaims["sub"] = username
        return convertedClaims
    }
}
```

然后,实例可以像正常情况一样提供:

Java

```
@Bean
JwtDecoder jwtDecoder() {
    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
    jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
    return jwtDecoder;
}
```

Kotlin

```
@Bean
fun jwtDecoder(): JwtDecoder {
    val jwtDecoder: NimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
    jwtDecoder.setClaimSetConverter(UsernameSubClaimAdapter())
    return jwtDecoder
}
```

## 配置超时

默认情况下,Resource Server使用30秒的连接和套接字超时来与授权服务器进行协调。

在某些情况下,这可能太短了。此外,它没有考虑到更复杂的模式,比如后退和发现。

要调整资源服务器连接到授权服务器的方式,`NimbusJwtDecoder`接受`RestOperations`的实例:

Java

```
@Bean
public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
    RestOperations rest = builder
            .setConnectTimeout(Duration.ofSeconds(60))
            .setReadTimeout(Duration.ofSeconds(60))
            .build();

    NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build();
    return jwtDecoder;
}
```

Kotlin

```
@Bean
fun jwtDecoder(builder: RestTemplateBuilder): JwtDecoder {
    val rest: RestOperations = builder
            .setConnectTimeout(Duration.ofSeconds(60))
            .setReadTimeout(Duration.ofSeconds(60))
            .build()
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build()
}
```

另外,默认情况下,Resource Server会在内存中缓存授权服务器的JWK设置5分钟,你可能需要对其进行调整。此外,它没有考虑更复杂的缓存模式,比如驱逐或使用共享缓存。

要调整资源服务器缓存JWK集的方式,`NimbusJwtDecoder`接受`Cache`的实例:

Java

```
@Bean
public JwtDecoder jwtDecoder(CacheManager cacheManager) {
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
            .cache(cacheManager.getCache("jwks"))
            .build();
}
```

Kotlin

```
@Bean
fun jwtDecoder(cacheManager: CacheManager): JwtDecoder {
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
            .cache(cacheManager.getCache("jwks"))
            .build()
}
```

当给定一个`Cache`时,资源服务器将使用JWK设置的URI作为键,并使用JWK设置的JSON作为值。

|   |Spring 不是缓存提供程序,因此你需要确保包含适当的依赖项,比如`spring-boot-starter-cache`和你最喜欢的缓存提供程序。|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

|   |不管是套接字超时还是缓存超时,你可能希望直接使用Nimbus。要做到这一点,请记住<br/>附带一个构造函数,该构造函数接受Nimbus的`JWTProcessor`。|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

[OAuth2资源服务器](index.html)[不透明令牌](opaque-token.html)