中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

網(wǎng)站建設(shè)服務(wù)費(fèi)會(huì)計(jì)分錄品牌推廣方案案例

網(wǎng)站建設(shè)服務(wù)費(fèi)會(huì)計(jì)分錄,品牌推廣方案案例,招標(biāo)網(wǎng)站哪個(gè)好用,樂清住房和城鄉(xiāng)建設(shè)部網(wǎng)站官網(wǎng)目錄 一、JWT的最小依賴 二、JWT的最基本配置 1、指定授權(quán)服務(wù)器 2、初始預(yù)期(Startup Expectations) 3、運(yùn)行時(shí)預(yù)期(Runtime Expectations) 三、JWT認(rèn)證是如何工作的 四、直接指定授權(quán)服務(wù)器 JWK Set Uri 五、提供 audie…

目錄

一、JWT的最小依賴

二、JWT的最基本配置

1、指定授權(quán)服務(wù)器

2、初始預(yù)期(Startup Expectations)

3、運(yùn)行時(shí)預(yù)期(Runtime Expectations)

三、JWT認(rèn)證是如何工作的

四、直接指定授權(quán)服務(wù)器 JWK Set Uri

五、提供 audiences

六、覆蓋或取代啟動(dòng)自動(dòng)配置

1、使用jwkSetUri()

2、使用decoder()

3、暴露一個(gè)JwtDecoder@Bean

七、配置受信任的算法

1、通過Spring Boot實(shí)現(xiàn)

2、使用 Builder

3、來自 JWK Set 的響應(yīng)

八、信任單一非對(duì)稱密鑰

1、通過 Spring Boot 實(shí)現(xiàn)

2、使用 Builder

九、信任單一對(duì)稱密鑰

十、配置 Authorization(授權(quán))

1、手動(dòng)提取權(quán)限

十一、配置驗(yàn)證

1、自定義時(shí)間戳驗(yàn)證

2、配置自定義驗(yàn)證器(Validator)

十二、配置 Claim 集映射

1、定制單一 Claim 的轉(zhuǎn)換

2、添加 Claim

3、刪除 Claim

4、重命名 Claim

5、配置超時(shí)


一、JWT的最小依賴

大多數(shù)資源服務(wù)器支持被收集到 spring-security-oauth2-resource-server 中。然而,對(duì)JWT的解碼和驗(yàn)證的支持是在 spring-security-oauth2-jose 中,這意味著為了擁有一個(gè)支持JWT編碼的 Bearer Token 的工作資源服務(wù)器,兩者都是必要的。

二、JWT的最基本配置

在使用 Spring Boot 時(shí),將一個(gè)應(yīng)用程序配置為資源服務(wù)器包括兩個(gè)基本步驟。首先,包括所需的依賴,其次,指定授權(quán)服務(wù)器的位置。

1、指定授權(quán)服務(wù)器

在Spring Boot應(yīng)用程序中,要指定使用哪一個(gè)授權(quán)服務(wù)器,只需:

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

其中 idp.example.com/issuer,是授權(quán)服務(wù)器將發(fā)出的JWT令牌的 iss claim 中包含的值。資源服務(wù)器將使用這個(gè)屬性來進(jìn)一步自我配置,發(fā)現(xiàn)授權(quán)服務(wù)器的公鑰,并隨后驗(yàn)證傳入的 JWT。

要使用 issuer-uri 屬性,還必須是 idp.example.com/issuer/.well-known/openid-configuration、idp.example.com/.well-known/openid-configuration/issuer 或 idp.example.com/.well-known/oauth-authorization-server/issuer 中的一個(gè)是授權(quán)服務(wù)器的支持端點(diǎn)。這個(gè)端點(diǎn)被稱為 提供者配置 端點(diǎn)或 授權(quán)服務(wù)器元數(shù)據(jù) 端點(diǎn)。

就這樣!

2、初始預(yù)期(Startup Expectations)

當(dāng)使用該屬性和這些依賴關(guān)系時(shí),資源服務(wù)器將自動(dòng)配置自己以驗(yàn)證JWT編碼的Bearer Token。

它通過一個(gè)確定性的啟動(dòng)過程來實(shí)現(xiàn)這一點(diǎn)。

  1. 查詢提供者配置或授權(quán)服務(wù)器元數(shù)據(jù)端點(diǎn)的 jwks_url 屬性
  2. 查詢 jwks_url 端點(diǎn)的支持算法
  3. 配置驗(yàn)證策略,以查詢 jwks_url 中找到的算法的有效公鑰。
  4. 配置驗(yàn)證策略,根據(jù) idp.example.com,驗(yàn)證每個(gè)JWTs iss claim。

這個(gè)過程的一個(gè)結(jié)果是,授權(quán)服務(wù)器必須啟動(dòng)并接收請(qǐng)求,以便資源服務(wù)器成功啟動(dòng)。

如果在資源服務(wù)器查詢時(shí),授權(quán)服務(wù)器已經(jīng)停機(jī)(給定適當(dāng)?shù)某瑫r(shí)),那么啟動(dòng)將失敗。

3、運(yùn)行時(shí)預(yù)期(Runtime Expectations)

一旦應(yīng)用程序啟動(dòng),資源服務(wù)器將嘗試處理任何包含 Authorization: Bearer 頭的請(qǐng)求。

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

只要指定了這個(gè) scheme,資源服務(wù)器就會(huì)嘗試根據(jù) Bearer Token 規(guī)范來處理請(qǐng)求。

給定一個(gè)格式良好的JWT,資源服務(wù)器將:

  1. 根據(jù)啟動(dòng)期間從 jwks_url 端點(diǎn)獲得的公鑰驗(yàn)證其簽名,并與JWT相匹配。
  2. 驗(yàn)證JWT的 exp 和 nbf 時(shí)間戳以及JWT的 iss claim。
  3. 將每個(gè) scope 映射到一個(gè)前綴為 SCOPE_ 的授權(quán)。

隨著授權(quán)服務(wù)器提供新的密鑰,Spring Security將自動(dòng)輪換用于驗(yàn)證JWTs的密鑰。

由此產(chǎn)生的 Authentication#getPrincipal 默認(rèn)為Spring Security Jwt 對(duì)象,Authentication#getName 映射到JWT的 sub 屬性,如果有的話。

從這里,考慮跳轉(zhuǎn)到:

  • JWT認(rèn)證是如何工作的
  • 如何在不將資源服務(wù)器的啟動(dòng)與授權(quán)服務(wù)器的可用性掛鉤的情況下進(jìn)行配置
  • 如何在非Spring Boot的情況下進(jìn)行配置

三、JWT認(rèn)證是如何工作的

接下來,讓我們看看Spring Security用來支持基于servlet的應(yīng)用程序中的 JWT 認(rèn)證的架構(gòu)組件,比如我們剛才看到的那個(gè)。

JwtAuthenticationProvider 是一個(gè) AuthenticationProvider 實(shí)現(xiàn),利用 JwtDecoder 和 JwtAuthenticationConverter 來驗(yàn)證JWT。

讓我們來看看 JwtAuthenticationProvider 是如何在Spring Security中工作的。圖中解釋了數(shù)字中的 AuthenticationManager 在 讀取 Bearer Token時(shí)的工作細(xì)節(jié)。

Figure 1. JwtAuthenticationProvider Usage

讀取 Bearer Token 的認(rèn)證 Filter 將一個(gè) BearerTokenAuthenticationToken 傳遞給由 ProviderManager 實(shí)現(xiàn)的認(rèn)證管理器。

ProviderManager 被配置為使用一個(gè) JwtAuthenticationProvider 類型的 AuthenticationProvider。

JwtAuthenticationProvider 使用 JwtDecoder 對(duì) Jwt 進(jìn)行解碼、驗(yàn)證和確認(rèn)。

JwtAuthenticationProvider 然后使用 JwtAuthenticationConverter 將 Jwt 轉(zhuǎn)換為授予權(quán)限的集合(Collection )。

當(dāng)認(rèn)證成功時(shí),返回的 Authentication 是 JwtAuthenticationToken 類型的,并且有一個(gè) principal 是由配置的 JwtDecoder 返回的 Jwt。最終,返回的 JwtAuthenticationToken 將被認(rèn)證 Filter 設(shè)置在 SecurityContextHolder 上。

四、直接指定授權(quán)服務(wù)器 JWK Set Uri

如果授權(quán)服務(wù)器不支持任何配置端點(diǎn),或者如果資源服務(wù)器必須能夠獨(dú)立于授權(quán)服務(wù)器啟動(dòng),那么也可以提供 jwk-set-uri。

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

JWK Set uri不是標(biāo)準(zhǔn)化的,但通??梢栽谑跈?quán)服務(wù)器的文檔中找到。

因此,資源服務(wù)器在啟動(dòng)時(shí)將不會(huì)ping授權(quán)服務(wù)器。我們?nèi)匀恢付?issuer-uri,這樣資源服務(wù)器仍然會(huì)驗(yàn)證傳入的JWT的 iss claim。

This property can also be supplied directly on the DSL.

五、提供 audiences

如前所述,issuer-uri 屬性驗(yàn)證了 iss claim;這是誰發(fā)送的JWT。

Boot 還具有用于驗(yàn)證 aud claim 的 audiences 屬性;這是 JWT 的發(fā)送對(duì)象。

資源服務(wù)器的 audience 可以這樣表示:

spring:security:oauth2:resourceserver:jwt:issuer-uri: https://idp.example.comaudiences: https://my-resource-server.example.com

如果需要,你也可以 通過編程添加 aud 驗(yàn)證。

結(jié)果是,如果 JWT 的 iss claim 不是 idp.example.com,且其 aud claim 的列表中不包含 my-resource-server.example.com,則驗(yàn)證將失敗。

六、覆蓋或取代啟動(dòng)自動(dòng)配置

有兩個(gè) @Bean 是Spring Boot代表資源服務(wù)器生成的。

第一個(gè)是 SecurityFilterChain,它將應(yīng)用程序配置為資源服務(wù)器。當(dāng)包括 spring-security-oauth2-jose 時(shí),這個(gè) SecurityFilterChain 看起來像:

Default JWT Configuration

  • Java
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2ResourceServer((oauth2) -> oauth2.jwt(Customizer.withDefaults()));return http.build();
}

如果應(yīng)用程序沒有公開 SecurityFilterChain Bean,那么Spring Boot將公開上述的默認(rèn)bean。

替換它就像在應(yīng)用程序中公開該bean一樣簡單。

Custom JWT Configuration

  • Java
@Configuration
@EnableWebSecurity
public class MyCustomSecurityConfiguration {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/messages/**").hasAuthority("SCOPE_message:read").anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(myConverter())));return http.build();}
}

以上要求任何以 /messages/ 開頭的URL的scope為 message:read。

oauth2ResourceServer DSL上的方法也將覆蓋或取代自動(dòng)配置。

例如,Spring Boot 創(chuàng)建的第二個(gè) @Bean 是一個(gè) JwtDecoder,它 將 String token 解碼為 Jwt 的驗(yàn)證實(shí)例。

JWT Decoder

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

調(diào)用 JwtDecoders#fromIssuerLocation 就是調(diào)用提供者配置或授權(quán)服務(wù)器元數(shù)據(jù)端點(diǎn),以便導(dǎo)出JWK Set Uri。

如果應(yīng)用程序沒有暴露一個(gè) JwtDecoder Bean,那么Spring Boot將暴露上述默認(rèn)的 JwtDecoder。

它的配置可以用 jwkSetUri() 重寫或用 decoder() 替換。

或者,如果你根本沒有使用Spring Boot,那么這兩個(gè)組件—?filter chain 和 JwtDecoder 都可以用XML指定。

過濾器鏈(filter chain)是這樣指定的。

Default JWT Configuration

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

而 JwtDecoder 是這樣的:

JWT Decoder

  • Java
<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>

1、使用jwkSetUri()

授權(quán)服務(wù)器的 JWK Set Uri 可以 作為一個(gè)配置屬性 來配置,也可以在DSL中提供。

JWK Set Uri Configuration

  • Java
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwkSetUri("https://idp.example.com/.well-known/jwks.json")));return http.build();}
}

使用 jwkSetUri() 優(yōu)先于任何配置屬性。

2、使用decoder()

比 jwkSetUri() 更強(qiáng)大的是 decoder(),它將完全取代 JwtDecoder 的任何Boot自動(dòng)配置。

JWT Decoder Configuration

  • Java
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwtDecoder {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.decoder(myCustomDecoder())));return http.build();}
}

當(dāng)需要更深入的配置時(shí),如 validation、mapping或request timeouts,這很方便。

3、暴露一個(gè)JwtDecoder@Bean

或者,暴露一個(gè)JwtDecoder @Bean 與 decoder() 有同樣的效果。

你可以像這樣用 jwkSetUri 構(gòu)建一個(gè):

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

或者你可以使用 issuer,并讓 NimbusJwtDecoder 在調(diào)用 build() 時(shí)查找 jwkSetUri,如下所示:

  • Java
@Bean
public JwtDecoder jwtDecoder() {return NimbusJwtDecoder.withIssuerLocation(issuer).build();
}

或者,如果默認(rèn)值對(duì)你有效,你也可以使用 JwtDecoders,除了配置 decoder 的驗(yàn)證器之外,它還可以完成上述工作:

  • Java
@Bean
public JwtDecoders jwtDecoder() {return JwtDecoders.fromIssuerLocation(issuer);
}

七、配置受信任的算法

默認(rèn)情況下,NimbusJwtDecoder,以及資源服務(wù)器,將只信任和驗(yàn)證使用 RS256 的令牌。

你可以通過Spring Boot、NimbusJwtDecoder builder或從 JWK Set response 中定制。

1、通過Spring Boot實(shí)現(xiàn)

設(shè)置算法的最簡單方法是配置一個(gè)屬性。

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

2、使用 Builder

不過,為了獲得更大的權(quán)力,我們可以使用 NimbusJwtDecoder 附帶的一個(gè)構(gòu)建器。

  • Java
@Bean
JwtDecoder jwtDecoder() {return NimbusJwtDecoder.withIssuerLocation(this.issuer).jwsAlgorithm(RS512).build();
}

多次調(diào)用 jwsAlgorithm 將配置 NimbusJwtDecoder 以信任一種以上的算法,像這樣。

  • Java
@Bean
JwtDecoder jwtDecoder() {return NimbusJwtDecoder.withIssuerLocation(this.issuer).jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
}

或者,你可以調(diào)用 jwsAlgorithms。

  • Java
@Bean
JwtDecoder jwtDecoder() {return NimbusJwtDecoder.withIssuerLocation(this.issuer).jwsAlgorithms(algorithms -> {algorithms.add(RS512);algorithms.add(ES512);}).build();
}

3、來自 JWK Set 的響應(yīng)

由于 Spring Security 的 JWT 支持基于 Nimbus,因此你也可以使用它的所有強(qiáng)大功能。

例如,Nimbus有一個(gè) JWSKeySelector 實(shí)現(xiàn),它將根據(jù)JWK Set URI的響應(yīng)(Response)來選擇算法集。你可以用它來生成一個(gè) NimbusJwtDecoder,像這樣。

  • Java
@Bean
public JwtDecoder jwtDecoder() {// makes a request to the JWK Set endpointJWSKeySelector<SecurityContext> jwsKeySelector =JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl);DefaultJWTProcessor<SecurityContext> jwtProcessor =new DefaultJWTProcessor<>();jwtProcessor.setJWSKeySelector(jwsKeySelector);return new NimbusJwtDecoder(jwtProcessor);
}

八、信任單一非對(duì)稱密鑰

比用JWK Set端點(diǎn)支持資源服務(wù)器更簡單的是硬編碼一個(gè)RSA公鑰。公鑰可以通過Spring Boot或 使用 Builder來提供。

1、通過 Spring Boot 實(shí)現(xiàn)

通過Spring Boot指定一個(gè)密鑰是非常簡單的。密鑰的位置可以像這樣指定。

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

或者,為了能夠進(jìn)行更復(fù)雜的查詢,你可以用 RsaKeyConversionServicePostProcessor 進(jìn)行后處理。

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

指定你的key的位置。

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

然后自動(dòng)注入value。

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

2、使用 Builder

要直接連接一個(gè) RSAPublicKey,你可以簡單地使用適當(dāng)?shù)?NimbusJwtDecoder builder,像這樣。

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

九、信任單一對(duì)稱密鑰

使用單一的對(duì)稱密鑰也很簡單。你可以簡單地加載你的 SecretKey 并使用適當(dāng)?shù)?NimbusJwtDecoder builder,像這樣。

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

十、配置 Authorization(授權(quán))

從OAuth 2.0授權(quán)服務(wù)器發(fā)出的JWT通常會(huì)有一個(gè) scope 或 scp 屬性,表明它被授予的scope(或權(quán)限),例如:

{ …?, "scope" : "messages contacts"}

當(dāng)出現(xiàn)這種情況時(shí),資源服務(wù)器將嘗試把這些scope強(qiáng)制性的成一個(gè)授予權(quán)限的列表,在每個(gè)scope前面加上 "SCOPE_" 字符串。

這意味著,要用從JWT派生的scope來保護(hù)一個(gè)端點(diǎn)或方法,相應(yīng)的表達(dá)式應(yīng)該包括這個(gè)前綴。

Authorization Configuration

  • Java
@Configuration
@EnableWebSecurity
public class DirectlyConfiguredJwkSetUri {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.requestMatchers("/contacts/**").hasAuthority("SCOPE_contacts").requestMatchers("/messages/**").hasAuthority("SCOPE_messages").anyRequest().authenticated()).oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);return http.build();}
}

或者類似于方法安全(method security)。

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

1、手動(dòng)提取權(quán)限

然而,在很多情況下,這個(gè)默認(rèn)值是不夠的。例如,有些授權(quán)服務(wù)器并不使用 scope 屬性,而是有自己的自定義屬性?;蛘?#xff0c;在其他時(shí)候,資源服務(wù)器可能需要將屬性或?qū)傩缘臉?gòu)成調(diào)整為內(nèi)部化的授權(quán)。

為此,Spring Security提供了 JwtAuthenticationConverter,它負(fù)責(zé) 將 Jwt 轉(zhuǎn)換為 Authentication。默認(rèn)情況下,Spring Security會(huì)將 JwtAuthenticationProvider 與 JwtAuthenticationConverter 的默認(rèn)實(shí)例連接起來。

作為配置 JwtAuthenticationConverter 的一部分,你可以提供一個(gè)附屬的轉(zhuǎn)換器,從 Jwt 到授予權(quán)限集合(Collection)。

假設(shè)你的授權(quán)服務(wù)器在一個(gè)名為 authorities 的自定義 claim 中交流授權(quán)。在這種情況下,你可以配置 JwtAuthenticationConverter 應(yīng)該檢查的 claim,像這樣。

Authorities Claim Configuration

  • Java
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);return jwtAuthenticationConverter;
}

你也可以把權(quán)限的前綴配置成不同的。你可以像這樣把每個(gè)權(quán)限的前綴改為 ROLE_,而不是用 SCOPE_。

Authorities Prefix Configuration

  • Java
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);return jwtAuthenticationConverter;
}

或者,你可以通過調(diào)用 JwtGrantedAuthoritiesConverter#setAuthorityPrefix("") 完全刪除前綴。

為了提高靈活性,DSL支持用任何實(shí)現(xiàn) Converter<Jwt, AbstractAuthenticationToken> 的類來完全替換converter。

  • Java
static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {public AbstractAuthenticationToken convert(Jwt jwt) {return new CustomAuthenticationToken(jwt);}
}// ...@Configuration
@EnableWebSecurity
public class CustomAuthenticationConverterConfig {@Beanpublic SecurityFilterChain filterChain(HttpSecurity http) throws Exception {http.authorizeHttpRequests(authorize -> authorize.anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(new CustomAuthenticationConverter())));return http.build();}
}

十一、配置驗(yàn)證

使用 最小的Spring Boot配置,表明授權(quán)服務(wù)器的發(fā)行者URI,資源服務(wù)器將默認(rèn)驗(yàn)證 iss claim 以及 exp 和 nbf 時(shí)間戳 claim。

在需要定制驗(yàn)證的情況下,資源服務(wù)器會(huì)提供兩個(gè)標(biāo)準(zhǔn)的驗(yàn)證器,同時(shí)也接受自定義的 OAuth2TokenValidator 實(shí)例。

1、自定義時(shí)間戳驗(yàn)證

JWT通常有一個(gè)有效期,開始時(shí)間在 nbf claim 中指出,結(jié)束時(shí)間在 exp 聲明中指出。

然而,每臺(tái)服務(wù)器都可能經(jīng)歷時(shí)鐘漂移,這可能導(dǎo)致令牌在一臺(tái)服務(wù)器上顯示為過期,而在另一臺(tái)服務(wù)器上卻不是。隨著分布式系統(tǒng)中合作服務(wù)器數(shù)量的增加,這可能會(huì)造成一些實(shí)施上的困擾。

資源服務(wù)器使用 JwtTimestampValidator 來驗(yàn)證令牌的有效性,它可以配置一個(gè) 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;
}

默認(rèn)情況下,資源服務(wù)器配置的時(shí)鐘偏移為60秒。

2、配置自定義驗(yàn)證器(Validator)

使用 OAuth2TokenValidator API,添加 aud claim 的檢查很簡單。

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

或者,為了更多的控制,你可以實(shí)現(xiàn)你自己的 OAuth2TokenValidator。

  • Java
static class AudienceValidator implements OAuth2TokenValidator<Jwt> {OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);@Overridepublic OAuth2TokenValidatorResult validate(Jwt jwt) {if (jwt.getAudience().contains("messaging")) {return OAuth2TokenValidatorResult.success();} else {return OAuth2TokenValidatorResult.failure(error);}}
}// ...OAuth2TokenValidator<Jwt> audienceValidator() {return new AudienceValidator();
}

然后,為了添加到資源服務(wù)器中,只需指定 JwtDecoder 實(shí)例即可。

  • 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;
}

如前所述,你可以在 Boot 中 配置 aud 驗(yàn)證。

十二、配置 Claim 集映射

Spring Security使用 Nimbus 庫來解析JWT并驗(yàn)證其簽名。因此,Spring Security受制于Nimbus對(duì)每個(gè)字段值的解釋,以及如何將每個(gè)字段強(qiáng)制成一個(gè)Java類型。

例如,由于Nimbus仍然與Java 7兼容,它不使用 Instant 來表示時(shí)間戳字段。

而且,完全可以使用不同的庫或用于JWT處理,它可能會(huì)做出自己的強(qiáng)制決定,需要進(jìn)行調(diào)整。

或者,很簡單,資源服務(wù)器可能想出于特定領(lǐng)域的原因從JWT中添加或刪除claim。

為了這些目的,資源服務(wù)器支持用 MappedJwtClaimSetConverter 映射JWT請(qǐng)求集。

1、定制單一 Claim 的轉(zhuǎn)換

默認(rèn)情況下,MappedJwtClaimSetConverter 將試圖將 claim 強(qiáng)制為以下類型。

Claim

Java 類型

aud

Collection<String>

exp

Instant

iat

Instant

iss

String

jti

String

nbf

Instant

sub

String

可以使用 MappedJwtClaimSetConverter.withDefaults 來配置單個(gè) claim 的轉(zhuǎn)換策略。

  • Java
@Bean
JwtDecoder jwtDecoder() {NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));jwtDecoder.setClaimSetConverter(converter);return jwtDecoder;
}

這將保持所有的默認(rèn)值,除了它將覆蓋 sub 的默認(rèn) claim converter。

2、添加 Claim

MappedJwtClaimSetConverter 也可以用來添加一個(gè)自定義的 claim,例如,為了適應(yīng)現(xiàn)有的系統(tǒng)。

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

3、刪除 Claim

刪除claim也很簡單,使用相同的API。

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

4、重命名 Claim

在更復(fù)雜的情況下,如同時(shí)咨詢多個(gè)claim或重命名一個(gè)claim,資源服務(wù)器接受任何實(shí)現(xiàn) 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;}
}

然后,可以像正常一樣提供實(shí)例。

  • Java
@Bean
JwtDecoder jwtDecoder() {NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).build();jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());return jwtDecoder;
}

5、配置超時(shí)

默認(rèn)情況下,資源服務(wù)器使用連接和套接字超時(shí)30秒來與授權(quán)服務(wù)器進(jìn)行協(xié)調(diào)。

這在某些情況下可能太短了。此外,它沒有考慮到更復(fù)雜的模式,如退訂和發(fā)現(xiàn)。

為了調(diào)整資源服務(wù)器連接到授權(quán)服務(wù)器的方式,NimbusJwtDecoder 接受了一個(gè) RestOperations 的實(shí)例。

  • Java
@Bean
public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {RestOperations rest = builder.setConnectTimeout(Duration.ofSeconds(60)).setReadTimeout(Duration.ofSeconds(60)).build();NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withIssuerLocation(issuer).restOperations(rest).build();return jwtDecoder;
}

另外,默認(rèn)情況下,資源服務(wù)器會(huì)在內(nèi)存中緩存授權(quán)服務(wù)器的JWK集5分鐘,你可能想調(diào)整一下。此外,它沒有考慮到更復(fù)雜的緩存模式,如驅(qū)逐或使用共享緩存。

為了調(diào)整資源服務(wù)器緩存JWK集的方式,NimbusJwtDecoder 接受一個(gè) Cache 的實(shí)例。

  • Java
@Bean
public JwtDecoder jwtDecoder(CacheManager cacheManager) {return NimbusJwtDecoder.withIssuerLocation(issuer).cache(cacheManager.getCache("jwks")).build();
}

當(dāng)給定一個(gè) Cache 時(shí),資源服務(wù)器將使用JWK Set Uri作為鍵,JWK Set JSON作為值。

Spring不是一個(gè)緩存提供者,所以你需要確保包含適當(dāng)?shù)囊蕾囮P(guān)系,比如 spring-boot-starter-cache 和你喜歡的緩存提供者。

無論是套接字還是緩存超時(shí),你可能反而想直接與Nimbus合作。要做到這一點(diǎn),請(qǐng)記住 NimbusJwtDecoder 有一個(gè)構(gòu)造函數(shù),它接收 Nimbus 的 JWTProcessor。

http://www.risenshineclean.com/news/38911.html

相關(guān)文章:

  • 佛山企業(yè)網(wǎng)站搭建公司百度認(rèn)證
  • 贛州網(wǎng)站優(yōu)化公司網(wǎng)站分析
  • 網(wǎng)站建設(shè)網(wǎng)頁設(shè)計(jì)用什么軟件當(dāng)下最流行的營銷方式
  • 秦皇島網(wǎng)站建設(shè)價(jià)格我要推廣網(wǎng)
  • 麗水網(wǎng)站建設(shè)哪家好網(wǎng)址導(dǎo)航哪個(gè)好
  • 做系統(tǒng)網(wǎng)站化學(xué)sem是什么意思
  • 最牛的手機(jī)視頻網(wǎng)站建設(shè)免費(fèi)的網(wǎng)站軟件
  • 自己做的網(wǎng)站字體變成方框18歲以上站長統(tǒng)計(jì)
  • 網(wǎng)站建設(shè)總體規(guī)劃百度云官網(wǎng)
  • 不登陸不收費(fèi)的網(wǎng)站鏈接seo優(yōu)化一般優(yōu)化哪些方面
  • 可以做外鏈的音樂網(wǎng)站百度廣告聯(lián)盟app下載官網(wǎng)
  • 如何給公司取一個(gè)好名字優(yōu)化網(wǎng)站關(guān)鍵詞優(yōu)化
  • ps中網(wǎng)站頁面做多大的豬八戒網(wǎng)接單平臺(tái)
  • 彩票計(jì)劃網(wǎng)站開發(fā)哪里有競(jìng)價(jià)推廣托管
  • 淘寶客優(yōu)惠卷網(wǎng)站怎么做的百度官方網(wǎng)首頁
  • 個(gè)性網(wǎng)站功能百度推廣服務(wù)費(fèi)3000元
  • 錦溪網(wǎng)站建設(shè)百度云搜索引擎官方入口
  • seo建設(shè)網(wǎng)站百度seo招聘
  • 中山做網(wǎng)絡(luò)推廣的公司廣告優(yōu)化師工資一般多少
  • 做推廣優(yōu)化的網(wǎng)站有哪些寧波最好的推廣平臺(tái)
  • wordpress站點(diǎn)臨時(shí)關(guān)閉seo自然優(yōu)化排名技巧
  • 做商城網(wǎng)站哪里買寧波seo推廣推薦公司
  • icp網(wǎng)站負(fù)責(zé)人網(wǎng)絡(luò)推廣平臺(tái)都有哪些
  • 甘南州住房和城鄉(xiāng)建設(shè)局網(wǎng)站百度一下就知道百度首頁
  • 寧波企業(yè)網(wǎng)站搭建特點(diǎn)百度一下百度一下你知道
  • 網(wǎng)站制作多久能完成廣州優(yōu)化疫情防控措施
  • 深圳做網(wǎng)站的網(wǎng)絡(luò)公2022年傳銷最新消息
  • 做曖曖視頻網(wǎng)站下載東營網(wǎng)站建設(shè)制作
  • 什么網(wǎng)站做微信公眾賬號(hào)seo專員工作容易學(xué)嗎
  • 做像素畫的網(wǎng)站岳陽seo公司