spring -security创建指定的用户和密码

一,创建spring项目,
在这里插入图片描述

二、创建SpringSecurityConfig继承WebSecurityConfigAdapter

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //此方法在5.X过时需要提供一个PasswordEncorder的实例,否则后台汇报错误:java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

        //auth.inMemoryAuthentication().withUser("admin").password("123456").roles("ADMIN");
        auth.inMemoryAuthentication().passwordEncoder(new MyPasswordEncoder()).withUser("admin").password("123456").roles("ADMIN");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**","/css/**","/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
             .anyRequest().authenticated()
             .and()
             .logout()
             .and()
             .formLogin();
        http.csrf().disable();
    }

三、创建PasswordEncorder的实例

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
    
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        
        return encodedPassword.equals(rawPassword.toString());
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_44048668/article/details/109636100
今日推荐