springsecurity 修改默认用户名密码三种方法

545 阅读1分钟

springsecurity 默认用户名是user, 默认密码启动时通过uuid生成的,如果需要修改默认用户名密码有以下三种方式

一、 通过配置文件

在application.yml文件中配置


spring:
  security:
    user:
      name: admin
      password: 123456

二、 通过配置类



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configurable
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //新版本的Spring Security要求必须为用户配置提供编码器,否则会报找不到相应的编码器错误。这里有个不是很重要的知识点,
        // 假如我们没有调用passwordEncoder方法为用户验证指明编码器,那么有一种替代方案,就是在密码前加"{noop}"等前缀,
        // 跟踪源码发现,框架会自动解析{}中的key去匹配相应的编码器
        auth.inMemoryAuthentication()
                .withUser("simm").password("{noop}123").roles("USER").and()
                .withUser("user").password(passwordEncoder().encode("123456")).roles("USER").and()
                .withUser("admin").password("{noop}admin").roles("USER", "ADMIN");

//        auth.inMemoryAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance())
//                .withUser("simm").password("123").roles("USER").and()
//                .withUser("admin").password("admin").roles("USER","ADMIN");
    }


}

三、自定义编写实现类

@Service("userDetailsService")
public class UserServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("USER");
        return new User("dasan", new BCryptPasswordEncoder().encode("123"), auths);
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}