Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

43.11. 常见问题

43.11.1. The Java/XML config for Spring MVC and Spring WebFlux cannot both be enabled, e.g. via @EnableWebMvc and @EnableWebFlux, in the same application.

是用 @EnableWebFlux 注解是,出现错误。这是因为 Mvc 与 Webflux 不能同时启用,通过下面配置可以解决。

			
spring.main.web-application-type=reactive
			
		

43.11.2. @EnableWebFluxSecurity 与 @EnableReactiveMethodSecurity 不生效

Mvc 不能与 Webflux 同时存在,默认系统是 Mvc 导致 Security 在 Webflux 下工作不正常。

去掉 Mvc 依赖

			
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>			
			
		

删除 @EnableWebSecurity 注解

			
@EnableWebMvc			
@EnableWebSecurity
			
		

增加配置

			
spring.main.web-application-type=reactive
			
		
			
package cn.netkiller.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.server.SecurityWebFilterChain;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {

    @Bean
    public MapReactiveUserDetailsService userDetailsService() {
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("user")
                .password("user")
                .roles("USER")
                .build();
        return new MapReactiveUserDetailsService(user);
    }

    @Order(Ordered.HIGHEST_PRECEDENCE)
    @Bean
    SecurityWebFilterChain filterChain(ServerHttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeExchange(exchanges -> exchanges
                        .anyExchange().authenticated()
                )
                .httpBasic(withDefaults())
                .formLogin(withDefaults());
        return httpSecurity.build();
    }

}
			
		

43.11.3. webflux netty 不支持 Content-Type: application/x-www-form-urlencoded

Post 数据无法使用 @RequestParam 读取,只能用于读取 URL 上的 GET 数据

		
[UnsupportedMediaTypeStatusException: 415 UNSUPPORTED_MEDIA_TYPE "Content type 'application/x-www-form-urlencoded' not supported"]