基于OpenID?Connect及Token?Relay實(shí)現(xiàn)Spring?Cloud?Gateway
前言
當(dāng)與Spring Security 5.2+ 和 OpenID Provider(如KeyClope)結(jié)合使用時(shí),可以快速為OAuth2資源服務(wù)器設(shè)置和保護(hù)Spring Cloud Gateway。
Spring Cloud Gateway旨在提供一種簡(jiǎn)單而有效的方式來(lái)路由到API,并為API提供跨領(lǐng)域的關(guān)注點(diǎn),如:安全性、監(jiān)控/指標(biāo)和彈性。
我們認(rèn)為這種組合是一種很有前途的基于標(biāo)準(zhǔn)的網(wǎng)關(guān)解決方案,具有理想的特性,例如對(duì)客戶端隱藏令牌,同時(shí)將復(fù)雜性保持在最低限度。
我們基于WebFlux的網(wǎng)關(guān)帖子探討了實(shí)現(xiàn)網(wǎng)關(guān)時(shí)的各種選擇和注意事項(xiàng),本文假設(shè)這些選擇已經(jīng)導(dǎo)致了上述問(wèn)題。
實(shí)現(xiàn)
我們的示例模擬了一個(gè)旅游網(wǎng)站,作為網(wǎng)關(guān)實(shí)現(xiàn),帶有兩個(gè)用于航班和酒店的資源服務(wù)器。我們使用Thymeleaf作為模板引擎,以使技術(shù)堆棧僅限于Java并基于Java。每個(gè)組件呈現(xiàn)整個(gè)網(wǎng)站的一部分,以在探索微前端時(shí)模擬域分離。
Keycloak
我們?cè)僖淮芜x擇使用keyclope作為身份提供者;盡管任何OpenID Provider都應(yīng)該工作。配置包括創(chuàng)建領(lǐng)域、客戶端和用戶,以及使用這些詳細(xì)信息配置網(wǎng)關(guān)。
網(wǎng)關(guān)
我們的網(wǎng)關(guān)在依賴關(guān)系、代碼和配置方面非常簡(jiǎn)單。
依賴項(xiàng)
- OpenID Provider的身份驗(yàn)證通過(guò)org.springframework.boot:spring-boot-starter-oauth2-client
- 網(wǎng)關(guān)功能通過(guò)org.springframework.cloud:spring-cloud-starter-gateway
- 將令牌中繼到代理的資源服務(wù)器來(lái)自org.springframework.cloud:spring-cloud-security
代碼
除了常見(jiàn)的@SpringBootApplication
注釋和一些web控制器endpoints之外,我們所需要的只是:
@Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ReactiveClientRegistrationRepository clientRegistrationRepository) { // Authenticate through configured OpenID Provider http.oauth2Login(); // Also logout at the OpenID Connect provider http.logout(logout -> logout.logoutSuccessHandler( new OidcClientInitiatedServerLogoutSuccessHandler(clientRegistrationRepository))); // Require authentication for all requests http.authorizeExchange().anyExchange().authenticated(); // Allow showing /home within a frame http.headers().frameOptions().mode(Mode.SAMEORIGIN); // Disable CSRF in the gateway to prevent conflicts with proxied service CSRF http.csrf().disable(); return http.build(); }
配置
配置分為兩部分;OpenID Provider的一部分。issuer uri屬性引用RFC 8414 Authorization Server元數(shù)據(jù)端點(diǎn)公開(kāi)的bij Keyclope。如果附加。您將看到用于通過(guò)openid配置身份驗(yàn)證的詳細(xì)信息。請(qǐng)注意,我們還設(shè)置了user-name-attribute
,以指示客戶機(jī)使用指定的聲明作為用戶名。
spring: security: oauth2: client: provider: keycloak: issuer-uri: http://localhost:8090/auth/realms/spring-cloud-gateway-realm user-name-attribute: preferred_username registration: keycloak: client-id: spring-cloud-gateway-client client-secret: 016c6e1c-9cbe-4ad3-aee1-01ddbb370f32
網(wǎng)關(guān)配置的第二部分包括到代理的路由和服務(wù),以及中繼令牌的指令。
spring: cloud: gateway: default-filters: - TokenRelay routes: - id: flights-service uri: http://127.0.0.1:8081/flights predicates: - Path=/flights/** - id: hotels-service uri: http://127.0.0.1:8082/hotels predicates: - Path=/hotels/**
TokenRelay
激活TokenRelayGatewayFilterFactory
,將用戶承載附加到下游代理請(qǐng)求。我們專門(mén)將路徑前綴匹配到與服務(wù)器對(duì)齊的server.servlet.context-path
。
測(cè)試
OpenID connect客戶端配置要求配置的提供程序URL在應(yīng)用程序啟動(dòng)時(shí)可用。為了在測(cè)試中解決這個(gè)問(wèn)題,我們使用WireMock記錄了keyclope響應(yīng),并在測(cè)試運(yùn)行時(shí)重播該響應(yīng)。一旦啟動(dòng)了測(cè)試應(yīng)用程序上下文,我們希望向網(wǎng)關(guān)發(fā)出經(jīng)過(guò)身份驗(yàn)證的請(qǐng)求。為此,我們使用Spring Security 5.0中引入的新SecurityMockServerConfigurers#authentication(Authentication)Mutator。使用它,我們可以設(shè)置可能需要的任何屬性;模擬網(wǎng)關(guān)通常為我們處理的內(nèi)容。
資源服務(wù)器
我們的資源服務(wù)器只是名稱不同;一個(gè)用于航班,另一個(gè)用于酒店。每個(gè)都包含一個(gè)顯示用戶名的最小web應(yīng)用程序,以突出顯示它已傳遞給服務(wù)器。
依賴項(xiàng)
我們添加了org.springframework.boot:spring-boot-starter-oauth2-resource-server到我們的資源服務(wù)器項(xiàng)目,它可傳遞地提供三個(gè)依賴項(xiàng)。
- 根據(jù)配置的OpenID Provider進(jìn)行的令牌驗(yàn)證通過(guò)org.springframework.security:spring-security-oauth2-resource-server
- JSON Web標(biāo)記使用org.springframework.security:spring-security-oauth2-jose
- 自定義令牌處理需要org.springframework.security:spring-security-config
代碼
我們的資源服務(wù)器需要更多的代碼來(lái)定制令牌處理的各個(gè)方面。
首先,我們需要掌握安全的基本知識(shí);確保令牌被正確解碼和檢查,并且每個(gè)請(qǐng)求都需要這些令牌。
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // Validate tokens through configured OpenID Provider http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter()); // Require authentication for all requests http.authorizeRequests().anyRequest().authenticated(); // Allow showing pages within a frame http.headers().frameOptions().sameOrigin(); } ... }
其次,我們選擇從keyclope令牌中的聲明中提取權(quán)限。此步驟是可選的,并且將根據(jù)您配置的OpenID Provider和角色映射器而有所不同。
private JwtAuthenticationConverter jwtAuthenticationConverter() { JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); // Convert realm_access.roles claims to granted authorities, for use in access decisions converter.setJwtGrantedAuthoritiesConverter(new KeycloakRealmRoleConverter()); return converter; } [...] class KeycloakRealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> { @Override public Collection<GrantedAuthority> convert(Jwt jwt) { final Map<String, Object> realmAccess = (Map<String, Object>) jwt.getClaims().get("realm_access"); return ((List<String>) realmAccess.get("roles")).stream() .map(roleName -> "ROLE_" + roleName) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } }
第三,我們?cè)俅翁崛?code>preferred_name作為身份驗(yàn)證名稱,以匹配我們的網(wǎng)關(guān)。
@Bean public JwtDecoder jwtDecoderByIssuerUri(<a rel="external nofollow" target="_blank" >OAuth2</a>ResourceServerProperties properties) { String issuerUri = properties.getJwt().getIssuerUri(); NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder) JwtDecoders.fromIssuerLocation(issuerUri); // Use preferred_username from claims as authentication name, instead of UUID subject jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter()); return jwtDecoder; } [...] class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> { private final MappedJwtClaimSetConverter delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap()); @Override public Map<String, Object> convert(Map<String, Object> claims) { Map<String, Object> convertedClaims = this.delegate.convert(claims); String username = (String) convertedClaims.get("preferred_username"); convertedClaims.put("sub", username); return convertedClaims; } }
配置
在配置方面,我們又有兩個(gè)不同的關(guān)注點(diǎn)。
首先,我們的目標(biāo)是在不同的端口和上下文路徑上啟動(dòng)服務(wù),以符合網(wǎng)關(guān)代理配置。
server: port: 8082 servlet: context-path: /hotels/
其次,我們使用與網(wǎng)關(guān)中相同的頒發(fā)者uri配置資源服務(wù)器,以確保令牌被正確解碼和驗(yàn)證。
spring: security: oauth2: resourceserver: jwt: issuer-uri: http://localhost:8090/auth/realms/spring-cloud-gateway-realm
測(cè)試
酒店和航班服務(wù)在如何實(shí)施測(cè)試方面都采取了略有不同的方法。Flights服務(wù)將JwtDecoder bean交換為模擬。相反,酒店服務(wù)使用WireMock回放記錄的keyclope響應(yīng),允許JwtDecoder正常引導(dǎo)。兩者都使用Spring Security 5.2中引入的new jwt()RequestPostProcessor來(lái)輕松更改jwt特性。哪種風(fēng)格最適合您,取決于您想要具體測(cè)試的JWT處理的徹底程度和方面。
結(jié)論
有了所有這些,我們就有了功能網(wǎng)關(guān)的基礎(chǔ)。它將用戶重定向到keydeport進(jìn)行身份驗(yàn)證,同時(shí)對(duì)用戶隱藏JSON Web令牌。對(duì)資源服務(wù)器的任何代理請(qǐng)求都使用適當(dāng)?shù)?code>access_token來(lái)豐富,該token令牌經(jīng)過(guò)驗(yàn)證并轉(zhuǎn)換為JwtAuthenticationToken,以用于訪問(wèn)決策。
到此這篇關(guān)于基于OpenID Connect及Token Relay實(shí)現(xiàn)Spring Cloud Gateway的文章就介紹到這了,更多相關(guān)Spring Cloud Gateway內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringCloud?GateWay網(wǎng)關(guān)示例代碼詳解
- SpringCloud?Gateway讀取Request?Body方式
- SpringCloud?Gateway之請(qǐng)求應(yīng)答日志打印方式
- springcloud gateway網(wǎng)關(guān)服務(wù)啟動(dòng)報(bào)錯(cuò)的解決
- springCloud gateWay 統(tǒng)一鑒權(quán)的實(shí)現(xiàn)代碼
- Spring?Cloud?Gateway整合sentinel?實(shí)現(xiàn)流控熔斷的問(wèn)題
- SpringCloud中Gateway實(shí)現(xiàn)鑒權(quán)的方法
相關(guān)文章
基于Ajax用戶名驗(yàn)證、服務(wù)條款加載、驗(yàn)證碼生成的實(shí)現(xiàn)方法
本篇文章對(duì)Ajax用戶名驗(yàn)證、服務(wù)條款加載、驗(yàn)證碼生成的實(shí)現(xiàn)方法,進(jìn)行了詳細(xì)的分析介紹。需要的朋友參考下2013-05-05idea +junit單元測(cè)試獲取不到bean注入的解決方式
這篇文章主要介紹了idea +junit單元測(cè)試獲取不到bean注入的解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08解決springboot+shiro+thymeleaf頁(yè)面級(jí)元素的權(quán)限控制問(wèn)題
這篇文章主要介紹了解決springboot+shiro+thymeleaf頁(yè)面級(jí)元素的權(quán)限控制問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01不使用他人jar包情況下優(yōu)雅的進(jìn)行dubbo調(diào)用詳解
這篇文章主要為大家介紹了不使用他人jar包情況下優(yōu)雅的進(jìn)行dubbo調(diào)用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09