Three ways to configure Spring Security's login user password

The dependencies needed before this and other configuration
maven dependencies

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
            <version>2.0.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

Other configuration

server.port=8081

spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

index page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    hello security
</body>
</html>

Controller

@Controller
@RequestMapping("/test")
public class TestController {
    
    
    @RequestMapping("/index")
    public String index(){
    
    
        return "index";
    }
}

Method 1: Configure users and passwords through configuration files

#方式一:配置配置文件
spring.security.user.name=zhangsan
spring.security.user.password=zhangsan

running result:
Insert picture description here

Method 2: Inherit the WebSecurityConfigurerAdapter through the configuration class to rewrite the configure(WebSecurity web) method

Note: To encrypt the password when configuring the password, you need to use PasswordEncoder to encrypt the password, otherwise an error will be reported, the error is as follows
: java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

Configuration class:

/**
 * 方式二:通过配置类继承WebSecurityConfigurerAdapter重写其中configure(WebSecurity web)方法
 * 注意:在配置密码时要加密需要使用PasswordEncoder来对密码进行加密,否则会报错,错误如下
 *      java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String passw = passwordEncoder.encode("123");
        auth.inMemoryAuthentication().withUser("lisi").password("123").roles("admin");
        //也可通过jdbc获取用户密码
        //auth.jdbcAuthentication()
    }
    @Bean
    public PasswordEncoder encoder(){
    
    
        return new BCryptPasswordEncoder();
    }
}

operation result
Insert picture description here

Method 3: Customize implementation class settings through UserDetailsService (used more often)

**Step 1: Create a configuration class and configure which UserDetailsService to use **

/**
 * 方式三:通过UserDetailsService自定义实现类设置
 */
@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
    
    

    @Autowired
    private UserDetailsService userDetailsService;

    public void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
    }
    @Bean
    public PasswordEncoder encoder(){
    
    
        return new BCryptPasswordEncoder();
    }
}

Step 2: Implement the UserDetailsService class

@Service("userDetailsService")
public class MyUserDetailsService implements Use![在这里插入图片描述](https://img-blog.csdnimg.cn/20210113095204779.gif#pic_center)
rDetailsService {
    
    
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    
    
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        //权限不能为空,一般是从数据库中读取
        return new User("zhaoliu",new BCryptPasswordEncoder().encode("abcde"),auths);
    }
}

running result:
Insert picture description here

Guess you like

Origin blog.csdn.net/magicproblem/article/details/112553097