使用springboot结合springsecurity搭建项目
我们先简单来写一个普通的springboot项目进行用户的查询
1.创建用户表
// 建表语句 DROp TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `role` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `status` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; //插入用户信息 INSERT INTO `sys_user` VALUES (1, 'user', 'user123', 'user', NULL); INSERT INTO `sys_user` VALUES (2, 'admin', 'admin123', 'admin', NULL);
2.创建用户实体类
@Data
public class SysUser {
private Integer id;
private String username;
private String password;
private Integer status;
private String role;
private String token;
}
3.使用mybatis实现用户的查询
@Mapper
public interface UserMapper {
@Select("select * from sys_user where username = #{username}")
SysUser getUserInfoByUsername(String username);
@Insert("insert into sys_user(username, password, role) value(#{username}, #{password}, #{role})")
int insertUser(SysUser user);
@Update("update sys_user set password = #{newPwd} where username = #{username}")
int updateUser(String username,String newPwd);
}
4.创建一个简单是controller控制器
@RestController
@RequestMapping("/product")
public class ProductController {
@GetMapping("/findAll")
public String findAll(){
return "返回所有列表";
}
@Autowired
private UserMapper userMapper;
@RequestMapping("/getsession")
public String getSession(HttpServletRequest request){
return request.getSession().toString();
}
@GetMapping("/getUser")
public SysUser getUser(@RequestParam String username){
return userMapper.getUserInfoByUsername(username);
}
@PreAuthorize("hasAnyRole('user')")
@GetMapping("/user")
public String user(){
UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(principal.toString());
return "user角色访问";
}
@PreAuthorize("hasAnyRole('admin')")
@GetMapping("/admin")
public String admin(){
return "admin管理员访问";
}
@Autowired
private PasswordEncoder passwordEncoder;
@PreAuthorize("hasAnyRole('admin')")
@PostMapping("/addUser")
public int addUser(@RequestBody SysUser user){
user.setPassword(passwordEncoder.encode(user.getPassword()));
return userMapper.insertUser(user);
}
@PutMapping("/updateUser")
public int updateUser(@RequestBody Map map){
// 获取当前登录用户信息(注意:没有密码的)
UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = principal.getUsername();
// 通过用户名获取到用户信息(获取密码)
SysUser userInfo = userMapper.getUserInfoByUsername(username);
// 判断输入的旧密码是正确
if (passwordEncoder.matches(map.get("oldPwd"), userInfo.getPassword())) {
// 不要忘记加密新密码
return userMapper.updateUser(username, passwordEncoder.encode(map.get("newPwd")));
}
return 0;
}
}
以上我们就用springboot结合mybatis完成了简单的web项目
下面我们导入springsecurity的maven包
org.springframework.boot spring-boot-starter-security
实现UserDetailsService——springsecurity加载用户的
@Component
public class CustomUserDetailsService implements UserDetailsService {
@Autowired
private UserMapper userMapper;
@Autowired
private PasswordEncoder passwordEncoder;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser sysUser = userMapper.getUserInfoByUsername(username);
if (sysUser == null) {
throw new UsernameNotFoundException("用户不存在");
}
String role = sysUser.getRole();
List authorities = new ArrayList<>();
// 这里加ROLE_ 是因为springsecurity的权限验证注解 是会在前面加ROLE_的
// 在AuthorityAuthorizationManager类中的hasRole可以看到
authorities.add(new SimpleGrantedAuthority("ROLE_"+ role));
// 如果在数据库中密码已经加密 这里是passwordEncoder.encode就不需要了
return new User(
sysUser.getUsername(),
passwordEncoder.encode(sysUser.getPassword()),
authorities
);
}
}
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全验证
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
// 用户账号密码 验证方法
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers(HttpMethod.POST,"/product/addUser").permitAll() // 允许addUser地址访问 无需认证
.anyRequest().authenticated() // 所有请求都需要验证
.and()
.formLogin().loginProcessingUrl("/login") //使用默认登录页面
.and()
.csrf().disable(); // post请求页面关闭csrf验证,不然访问报错,实际开发中开启,需要前端配合传递其他参数
}
}
springsecurity的包导入之后 发起请求之后,不管是login接口还是其他接口,都会给浏览器设置cookie,如下图所示 使用cookie也同样会给



