使用的技术有:mybatis-plus,spring-security,lombok
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
Users实体类
@Data
public class Users {
private Integer id;
private String username;
private String password;
}
SecurityConfig配置类
@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder password(){
return new BCryptPasswordEncoder();
}
protected void configure(HttpSecurity http) throws Exception{
http.formLogin() //自定义自己编写的登录页面
.loginPage("/login.html") //登录页面设置
.loginProcessingUrl("/user/login") //登录访问路径
.defaultSuccessUrl("/test/index").permitAll() //登录成功之后,跳转路径
.and().authorizeRequests()
.antMatchers("/","/test/hello","/user/login").permitAll() //设置哪些路径可以直接访问,不需要认证
.anyRequest().authenticated()
.and().csrf().disable(); //关闭csrf的防护
}
}
UsersMapper接口
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}
MyUserDetailsService 类
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UsersMapper usersMapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper<Users> wrapper = new QueryWrapper<>();
//where username=?
wrapper.eq("username", username);
Users users = usersMapper.selectOne(wrapper);
if (users == null) {//数据库没有用户名,认证失败
throw new UsernameNotFoundException("用户名不存在!");
}
List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
//从查询到的user中,得到用户名和密码
return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
}
}
Controller
@RestController
@RequestMapping("/test")
public class HelloController {
@GetMapping("/hello")
public String hello(){
return "hello security";
}
@GetMapping("/index")
public String index(){
return "hello index";
}
}
然后编写你的 login.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title>
</head>
<body>
<form action="/user/login" method="post">
用户名:<input type="text" name="username">
</br>
密码:<input type="password" name="password">
</br>
<input type="submit" value="login"/>
</form>
</body>
</html>
注意:
上面图中的name属性必须填写username和password,否则报错
启动类上不要忘记添加MapperScan注解