SecurityConfiguration.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright 2020 the original author or authors.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * https://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package example;
  17. import org.springframework.context.annotation.Bean;
  18. import org.springframework.context.annotation.Configuration;
  19. import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity;
  20. import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
  21. import org.springframework.security.config.web.server.ServerHttpSecurity;
  22. import org.springframework.security.core.userdetails.MapReactiveUserDetailsService;
  23. import org.springframework.security.core.userdetails.User;
  24. import org.springframework.security.core.userdetails.UserDetails;
  25. import org.springframework.security.web.server.SecurityWebFilterChain;
  26. import static org.springframework.security.config.Customizer.withDefaults;
  27. /**
  28. * Minimal method security configuration.
  29. *
  30. * @author Rob Winch
  31. * @since 5.0
  32. */
  33. @Configuration
  34. @EnableWebFluxSecurity
  35. @EnableReactiveMethodSecurity
  36. public class SecurityConfiguration {
  37. @Bean
  38. SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
  39. // @formatter:off
  40. http
  41. // Demonstrate that method security works
  42. // Best practice to use both for defense in depth
  43. .authorizeExchange((exchanges) -> exchanges
  44. .anyExchange().permitAll()
  45. )
  46. .httpBasic(withDefaults());
  47. // @formatter:on
  48. return http.build();
  49. }
  50. @Bean
  51. MapReactiveUserDetailsService userDetailsService() {
  52. // @formatter:off
  53. UserDetails user = User.withDefaultPasswordEncoder()
  54. .username("user")
  55. .password("password")
  56. .roles("USER")
  57. .build();
  58. UserDetails admin = User.withDefaultPasswordEncoder()
  59. .username("admin")
  60. .password("password")
  61. .roles("ADMIN", "USER")
  62. .build();
  63. // @formatter:on
  64. return new MapReactiveUserDetailsService(user, admin);
  65. }
  66. }