Spring Boot 2 security basic authentication

2020-05-01 04:26发布

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

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .httpBasic()
            .and()
            .authorizeRequests()
            .anyRequest().authenticated();
        super.configure(http);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser("username").password("password");
        super.configure(auth);
    }

}

After the application initialization, there is still only default user generated by Spring itself, there is no such user like username.

2条回答
走好不送
2楼-- · 2020-05-01 04:30

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();
    }
}  
查看更多
够拽才男人
3楼-- · 2020-05-01 04:51

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");
}
查看更多
登录 后发表回答