章节
- 不再视野黑盒,一天学会简单使用springboot(1) - 掘金 (juejin.cn)
- 不再视野黑盒,新建springboot项目(2) - 掘金 (juejin.cn)
- 不再视野黑盒,整合mybatis plus(3) - 掘金 (juejin.cn)
- 不再视野黑盒,统一结果封装(4) - 掘金 (juejin.cn)
- 不再视野黑盒,整合shiro+jwt,并会话共享(5) - 掘金 (juejin.cn)
- 不再视野黑盒,异常处理&实体校验(6) - 掘金 (juejin.cn)
- 不再视野黑盒,swagger3集成(7) - 掘金 (juejin.cn)
- 不再视野黑盒,登录&增删改查(8) - 掘金 (juejin.cn)
登录
登录的逻辑其实很简答,只需要接受账号密码,然后把用户的id生成jwt,返回给前段,为了后续的jwt的延期,所以我们把jwt放在header上。具体代码如下:
@RestController
public class AccountController {
@Autowired
UserService userService;
@Autowired
JwtUtils jwtUtils;
@PostMapping("/login")
public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
UserDemo user = userService.getOne(new QueryWrapper<UserDemo>().eq("username", loginDto.getUsername()));
Assert.notNull(user, "用户不存在");
if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
return Result.fail("密码不正确");
}
String jwt = jwtUtils.generateToken(user.getId());
response.setHeader("Authorization", jwt);
response.setHeader("Access-control-Expose-Headers", "Authorization");
return Result.succ(MapUtil.builder()
.put("id", user.getId())
.put("username", user.getUsername())
.put("avatar", user.getAvatar())
.put("email", user.getEmail())
.map()
);
}
@RequiresAuthentication
@GetMapping("/logout")
public Result logout() {
SecurityUtils.getSubject().logout();
return Result.succ(null);
}
}
增删改查
我们的骨架已经完成,接下来,我们就可以添加我们的业务接口了。
注意@RequiresAuthentication说明需要登录之后才能访问的接口,其他需要权限的接口可以添加shiro的相关注解。此处提供了基本增删改查。注意的是edit方法是需要登录才能操作的受限资源。
@RestController
@RequestMapping("/blog")
@Api(tags = "博客信息")
public class BlogController {
@Autowired
BlogService blogService;
// 分页查找
@GetMapping("/blog/list")
@Operation(summary = "分页查找")
public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
Page page = new Page(currentPage, 5);
IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("created"));
return Result.succ(pageData);
}
// 单查
@GetMapping("/blog/{id}")
@Operation(summary = "根据id查询")
public Result detail(@PathVariable("id") Long id){
Blog blog = blogService.getById(id);
Assert.notNull(blog,"未查找到该博客!");
return Result.succ(blog);
}
// 修改
@GetMapping("/blog/edit")
@Operation(summary = "修改博客")
public Result detail(@Validated @RequestBody Blog blog){
Blog temp = null;
if(blog.getId()!=null){
temp = blogService.getById(blog.getId());
Assert.isTrue(temp.getUserId() == ShiroUtil.getProfile().getId(),"没有编辑权限");
}else{
temp = new Blog();
temp.setUserId(ShiroUtil.getProfile().getId());
temp.setCreated(LocalDateTime.now());
temp.setStatus(0);
}
BeanUtil.copyProperties(blog,temp,"id","userId","created","status");
blogService.saveOrUpdate(temp);
return Result.succ(null);
}
}