账号密码登录模块
实现:已注册用户输入账号密码,在经过检验用户是否存在、密码验证后完成登录;
1. /**
2. * 用户名密码登录
3. * @param username
4. * @param password
5. * @return
6. */
7. @PostMapping("/login")
8. @ApiOperation("根据用户名和密码登录")
9. @ApiImplicitParams({
10. @ApiImplicitParam(name = "username",value = "用户名",required = true),
11. @ApiImplicitParam(name = "password",value = "密码",required = true)
12. }
13. )
14. public Result login(@RequestParam("username")String username,
15. @RequestParam("password")String password
16. ){
17. try{
18. User user=adminService.vertify(adminService.getUserByusername(username),password);
19.
20. String token=adminService.buildToken(username);
21.
22. redisTemplate.opsForValue().set(token,user, Duration.ofMinutes(120L));
23.
24. return new Result(user,"请求成功",100);
25. }catch (Exception e){
26.
27. return new Result(null,"请求异常",103);
28.
29. }
30. }
登录令牌模块
用户登录后将令牌与用户信息作为键值对存入Redis,设置有效时间,对其他接口的访问先检查令牌是否有效,否则过滤请求;
1. @WebFilter(urlPatterns = {"/*"})
2. public class LoginFilter implements Filter {
3.
4. @Resource
5. RedisTemplate<String,Object> redisTemplate;
6.
7. @Override
8. public void init(FilterConfig filterConfig) throws ServletException {
9.
10. }
11.
12. @Override
13. public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
14. //校验用户登录状态
15. HttpServletRequest request = (HttpServletRequest) servletRequest;
16. HttpServletResponse response = (HttpServletResponse) servletResponse;
17.
18. //Filter过滤器跨域处理
19. String origin = request.getHeader("Origin");
20. response.setHeader("Access-Control-Allow-Origin", origin);//允许域名请求
21. response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");//允许请求的方式
22. response.setHeader("Access-Control-Max-Age", "1800");//指定本次预检请求的有效期,单位为秒
23. response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token");//自定义请求头,放置token
24. response.setHeader("Access-Control-Allow-Credentials", "true");//页面中允许显示请求头
25.
26. //获取请求中的token
27. String token=request.getHeader("token");
28. token = token==null ? "" : token;
29.
30. //查询token在Redis中的剩余时间
31. Long expire = redisTemplate.getExpire(token);
32.
33. if(expire > 0){ //是登录状态
34.
35. redisTemplate.expire(token,60L, TimeUnit.MINUTES);//重置token的时间,保持登录信息有效
36.
37.
38.
39. filterChain.doFilter(servletRequest,servletResponse);//允许请求
40. }else {//登录状态失效
41. response.sendRedirect("/index.html");
42. }
43. }
权限认证模块
同在请求过滤器中限制;