Spring Boot 2 security basic authentication

后端 未结 2 1906
一向
一向 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();
        }
    }  
    
    0 讨论(0)
  • 2021-01-23 17:04

    Do not call super method from void configure(AuthenticationManagerBuilder auth). It sets disableLocalConfigureAuthenticationBldr flag to true that leads to your AuthenticationManagerBuilder being ignored. Finally your void configure(AuthenticationManagerBuilder auth) method should look like this:

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("username").password("password").roles("USER");
    }
    
    0 讨论(0)
提交回复
热议问题