首页 > 解决方案 > 在 Reactive spring security 中基于 url 模式应用不同的规则

问题描述

我有不同的端点组,如 API、登录和开放访问。

只想为登录端点触发 oauth。没有有效会话的 api 端点的 401 错误。

我试图放置多个 SecurityWebFilterChain 定义。但它不起作用。它为所有网址提供 401。

    @Bean
    @Order(1)
    public SecurityWebFilterChain openAccess(ServerHttpSecurity http) {
        http.authorizeExchange(
                exchanges ->
                        exchanges
                                .pathMatchers("/", "/ping", "/view/home", "/actuator/**")
                                .permitAll())
                .httpBasic()
                .disable()
                .formLogin()
                .disable()
                .csrf()
                .csrfTokenRepository(csrfTokenRepository());
        return http.build();
    }

    @Bean
    @Order(2)
    public SecurityWebFilterChain apiSecurity(ServerHttpSecurity http) {
        http.authorizeExchange(
                exchanges ->
                        exchanges
                                .pathMatchers("/api/user/")
                                .hasAuthority(
                                        PRODUCT
                                                .getAccessName()
                                                .toLowerCase()))
                .httpBasic()
                .disable()
                .formLogin()
                .disable()
                .csrf()
                .csrfTokenRepository(csrfTokenRepository());
        return http.build();
    }

    @Bean
    @Order(3)
    public SecurityWebFilterChain oauthAccess(ServerHttpSecurity http) {
        http.authorizeExchange(
                exchanges ->
                        exchanges
                                .pathMatchers("/kp/oauth2/**")
                                .permitAll()
                                .pathMatchers("/login")
                                .authenticated())
                .httpBasic()
                .disable()
                .formLogin()
                .disable()
                .csrf()
                .csrfTokenRepository(csrfTokenRepository())
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(
                        logoutSuccessHandler("/logout.com/logout?service=" + casServerUrl))
                .and()
                .oauth2Login();
        return http.build();
    }

以下是应用程序启动日志: https ://gist.github.com/rajeevprasanna/122b4e42f048b2c07eb80f60cd423f34

当我在浏览器中输入 URL http://localhost:8080/login时,出现 401 错误。希望它根据我的配置触发 OAuth 流程 https://gist.github.com/rajeevprasanna/aa0d586fc86cbd31e103c5c3f8a3fc06

更新:我尝试修改代码并添加了 securityMatcher。但在 oauth 身份验证方面遇到了不同的问题。问题单独发布: Spring security not redirecting to given OAuth authentication URL

标签: spring-securityspring-webfluxspring-security-oauth2

解决方案


推荐阅读