ตัวอย่างการเขียน Spring-boot WebFlux Security
pom.xml
...
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
...
@SpringBootApplication
@ComponentScan(basePackages = {"com.pamarin"})
public class AppStarter {
public static void main(String[] args) {
SpringApplication.run(AppStarter.class, args);
}
}
@Slf4j
@EnableWebFluxSecurity
public class SecurityConfig {
@Bean
public ReactiveUserDetailsService reactiveUserDetailsService(PasswordEncoder passwordEncoder) {
return username -> {
log.debug("login with username => {}", username);
return Mono.just(
User.withUsername(username)
.password(passwordEncoder.encode("password"))
.authorities(Collections.emptyList())
.build()
);
};
}
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
@EnableWebFluxSecurity
เป็นการ enable Spring Security- method passwordEncoder() เป็นการประกาศใช้ password encoder เป็น
BCryptPasswordEncoder
- method reactiveUserDetailsService() เป็นการประกาศ login service ว่าถ้ามีการ login เข้ามาให้ find user จาก username ที่ส่งมาใน service นี้ ซึ่งปกติจะ find จาก database ถ้าไม่เจอ อาจจะ throw error
org.springframework.security.authentication.BadCredentialsException
ออกไป - เบื้องต้น สิทธิ์ หรือ authorities กำหนดเป็น empty ไปก่อน
authorities(Collections.emptyList())
@RestController
public class HomeController {
@GetMapping({"", "/"})
public Mono<String> hello(Authentication authentication) {
return Mono.just("Hello => " + authentication.getName());
}
}
cd ไปที่ root ของ project จากนั้น
$ mvn clean install
$ mvn spring-boot:run
เปิด browser แล้วเข้า http://localhost:8080
หลังจากนั้นมันจะเด้งเข้าหน้า login (default จาก Spring Security)
- username = test
- password = password