准备:
sql数据
CREATE TABLE `users` (
`id` int NOT NULL,
`username` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`password` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
INSERT INTO `users` VALUES (1, 'lucy', '123');
INSERT INTO `users` VALUES (2, 'tom', '456');
pom文件
<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>
</dependency>
<!-- mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<!-- mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok简化实体类-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
properties配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
实体类
@Data
public class Users {
private Integer id;
private String username;
private String password;
}
mapper扫描
@SpringBootApplication
@MapperScan("com.example.springsecuritydemo01.mapper")
public class Springsecuritydemo01Application {
public static void main(String[] args) {
SpringApplication.run(Springsecuritydemo01Application.class, args);
}
}
UsersMapper
添加@Repository注解防止@Autowired注入时飘红,可不加
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}
配置类
@Configuration
public class SecurityConfigDiy extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
测试Controller
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/hello")
public String hello(){
return "hello security";
}
}
MyUserDetailService
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<Users> wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
Users users = usersMapper.selectOne(wrapper);
if(users == null){
throw new UsernameNotFoundException("用户名不存在!");
}
List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
return new User(users.getUsername(),new BCryptPasswordEncoder().encode(users.getPassword()),authorityList);
}
}