授權 ServerHttpRequest

Spring Security 提供授權傳入 HTTP 請求的支援。預設情況下,Spring Security 的授權會要求所有請求都經過身份驗證。明確的組態看起來像這樣

所有請求都需要經過身份驗證的使用者
  • Java

  • Kotlin

@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
    http
        .authorizeExchange(exchanges -> exchanges
            .anyExchange().authenticated()
        )
        .httpBasic(withDefaults())
        .formLogin(withDefaults());
    return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        authorizeExchange {
            authorize(anyExchange, authenticated)
        }
        formLogin { }
        httpBasic { }
    }
}

我們可以組態 Spring Security,透過依優先順序新增更多規則來設定不同的規則。

多個授權請求規則
  • Java

  • Kotlin

import static org.springframework.security.authorization.AuthorityReactiveAuthorizationManager.hasRole;
// ...
@Bean
SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
	http
		// ...
		.authorizeExchange((authorize) -> authorize                          (1)
			.pathMatchers("/resources/**", "/signup", "/about").permitAll()  (2)
			.pathMatchers("/admin/**").hasRole("ADMIN")                      (3)
			.pathMatchers("/db/**").access((authentication, context) ->      (4)
				hasRole("ADMIN").check(authentication, context)
					.filter(decision -> !decision.isGranted())
					.switchIfEmpty(hasRole("DBA").check(authentication, context))
			)
			.anyExchange().denyAll()                                         (5)
		);
	return http.build();
}
@Bean
fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
    return http {
        authorizeExchange {                                                           (1)
            authorize(pathMatchers("/resources/**", "/signup", "/about"), permitAll)  (2)
            authorize("/admin/**", hasRole("ADMIN"))                                  (3)
            authorize("/db/**", { authentication, context ->                          (4)
                hasRole("ADMIN").check(authentication, context)
                    .filter({ decision -> !decision.isGranted() })
                    .switchIfEmpty(hasRole("DBA").check(authentication, context))
            })
            authorize(anyExchange, denyAll)                                           (5)
        }
        // ...
    }
}
1 已指定多個授權規則。每個規則都按照宣告的順序進行考量。
2 我們指定了多個任何使用者都可以存取的 URL 模式。具體來說,如果 URL 以 "/resources/" 開頭、等於 "/signup" 或等於 "/about",則任何使用者都可以存取請求。
3 任何以 "/admin/" 開頭的 URL 將會限制為具有 "ROLE_ADMIN" 權限的使用者。您會注意到,由於我們正在調用 hasRole 方法,因此我們不需要指定 "ROLE_" 前綴。
4 任何以 "/db/" 開頭的 URL 都要求使用者同時具有 "ROLE_ADMIN" 和 "ROLE_DBA" 權限。這示範了提供自訂 ReactiveAuthorizationManager 的彈性,讓我們能夠實作任意授權邏輯。為了簡單起見,範例使用 Lambda 並委派給現有的 AuthorityReactiveAuthorizationManager.hasRole 實作。然而,在真實世界的情況中,應用程式可能會在實作 ReactiveAuthorizationManager 的適當類別中實作邏輯。
5 任何尚未比對到的 URL 都會被拒絕存取。如果您不想意外忘記更新授權規則,這是一個很好的策略。