我想了解以下代碼片段:
@Bean
fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain? {
val customPrincipalExtractor = SubjectDnX509PrincipalExtractor()
customPrincipalExtractor.setSubjectDnRegex("OU=(.*?)(?:,|$)")
val customAuthenticationManager = ReactiveAuthenticationManager { authentication: Authentication ->
authentication.isAuthenticated = "Trusted Org Unit" == authentication.name
Mono.just(authentication)
}
return http {
x509 {
principalExtractor = customPrincipalExtractor
authenticationManager = customAuthenticationManager
}
authorizeExchange {
authorize(anyExchange, authenticated)
}
}
}
來自https://docs.spring.io/spring-security/reference/5.6.1/reactive/authentication/x509.html。
我的問題是這個塊是什么意思?
http {
x509 {
principalExtractor = customPrincipalExtractor
authenticationManager = customAuthenticationManager
}
authorizeExchange {
authorize(anyExchange, authenticated)
}
}
這個怎么運作?
uj5u.com熱心網友回復:
這稱為型別安全的構建器模式。它在 Kotlin 中主要用于以宣告方式創建物件和/或通過庫提供 DSL。它是 Kotlin 最高級的特性之一,所以用幾句話來解釋并不容易,但上面的例子是這樣作業的:
http()是一個高階函式,它接收一個用于配置http物件的 lambda。http()執行此 lambda,為 lambda 提供某種“http 范圍”或“http builder”物件。Lambda 接收這個引數作為this,所以我們可以隱式訪問它的成員。(我不知道這個范圍/構建器物件的具體型別是什么,你可以通過控制點擊查看http)- Lambda 可以
http通過訪問提供的范圍/構建器的成員來配置正在創建的物件。x509()并且authorizeExchange()是它的構建器或擴展的成員。我們可以在http {}block 內無處呼叫它們,因為構建器是我們的this,所以它的所有成員都被隱式決議。 x509()并authorizeExchange()做同樣的事情http()。他們接受 lambda 并為 lambdas 提供另一個構建器。
uj5u.com熱心網友回復:
您詢問的代碼配置了彈簧安全性。您有一個ServerHttpSecurity名為的物件http,并且您正在對其進行配置。
它在普通 java 中的相等是這樣的:
http
.x509()
.principalExtractor(customPrincipalExtractor)
.authenticationManager(customAuthenticationManager)
.authorizeExchange()
.anyExchange()
.authenticated();
前三行表示我們將使用 x509 證書,我們有一個自定義主體提取器,我們定義了幾行,即SubjectDnX509PrincipalExtractor https://docs.spring.io/spring-security/site/docs/ 3.2.8.RELEASE/apidocs/org/springframework/security/web/authentication/preauth/x509/SubjectDnX509PrincipalExtractor.html,當我們從證書中提取資訊并構建我們的主體物件時需要使用(所有經過身份驗證的用戶都有包含他們是誰的主體,等等)
該特定提取器使用正則運算式來提取subject證書中定義的內容。
之后的行我們設定了一個自定義AuthenticationManager https://javadoc.io/doc/org.springframework.security/spring-security-core/latest/org/springframework/security/authentication/AuthenticationProvider.html
其中有幾個內置在 spring 中。例如,如果您想使用用戶名和密碼進行身份驗證,或者通過提供令牌或 cookie,或者通過提供證書,您可以使用特定的身份驗證管理器。或者,如果您想以特定方式對某人進行身份驗證,您可以撰寫一個自定義的。
最后三行表示任何交換(請求)都需要經過身份驗證。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/443196.html
