Spring Boot 2 security basic authentication

后端 未结 2 1913
一向
一向 2021-01-23 16:25

Why following basic security configurations do not apply inMemoryAuthentication() clause?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extend         


        
2条回答
  •  星月不相逢
    2021-01-23 16:44

    In spring boot 2.x, you will have to implement your own UserDetailsService, as described here and here

    Example:

    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        private static final Logger log = LogManager.getLogger();
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Note: 
            // Use this to enable the tomcat basic authentication (tomcat popup rather than spring login page)
            // Note that the CSRf token is disabled for all requests
            log.info("Disabling CSRF, enabling basic authentication...");
            http
            .authorizeRequests()
                .antMatchers("/**").authenticated() // These urls are allowed by any authenticated user
            .and()
                .httpBasic();
            http.csrf().disable();
        }
    
        @Bean
        public UserDetailsService userDetailsService() {
            // Get the user credentials from the console (or any other source): 
            String username = ...
            String password = ...
    
            // Set the inMemoryAuthentication object with the given credentials:
            InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
            String encodedPassword = passwordEncoder().encode(password);
            manager.createUser(User.withUsername(username).password(encodedPassword).roles("USER").build());
            return manager;
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }  
    

提交回复
热议问题