SpringBoot+Redis实现springsecurity

引入依赖:

<!--redis-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

cmd到redis的bin目录下执行redis-server redis.windows.conf

controller类

@Controller
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ManagerService managerService;
    //使用cookie需要传入HttpServletResponse response
    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response) {
        //1.与数据库里的数据匹配
        Manager manager=managerService.findManagerByUsernameAndPassword(username,password);
        if(manager==null){
            return "login/login";
        }
        //2,设置token到redis
        String token= UUID.randomUUID().toString();
        //设定redis过期时间
        Integer expire= RedisConstant.EXPIRE;
        //format格式化一下,希望token按照固定的模式
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX,token),username,expire, TimeUnit.SECONDS);
        //redisTemplate.opsForValue().set("abc","bdcancjasnc");
        //3,设置token到cookie
        CookieUtil.set(response, CookieConstant.TOKEN,token,expire);
        return "redirect:/users/user/list";
    }

    @GetMapping("/log")
    public String logout(HttpServletRequest request, HttpServletResponse response, Map<String,Object>map) {
    //将cookie和token删掉
        //1.从cookie里查询
       Cookie cookie= CookieUtil.get(request,CookieConstant.TOKEN);
        if(cookie!=null){
            //2.清除redis
           redisTemplate.opsForValue().getOperations().delete(String.format(RedisConstant.TOKEN_PREFIX,cookie.getValue()));
            //3.清除cookie(直接将时间设置为0)
            CookieUtil.set(response,CookieConstant.TOKEN,null,0);
        }
        return "login/login";
    }
}

 

RedisConstant.java
public interface RedisConstant {
    String TOKEN_PREFIX="token_%s";//储存的key以token_开头的
    Integer EXPIRE=7200;//两小时
}
CookieUtil.java
public class CookieUtil {
    /**
     * 设置cookie
     *
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void set(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");//路径是指http://127.0.0.1:8080这个路径下的网页cookie有效
        cookie.setMaxAge(maxAge);//过期时间
        response.addCookie(cookie);
    }

    /**
     * 获取cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie get(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = readCookieMap(request);
        //判断cookie中是否包含name
        if (cookieMap.containsKey(name)) {
            return cookieMap.get(name);
        } else {
            return null;
        }
    }

    /**
     * 将cookie封装成map
     * @param request
     * @return
     */
    private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<>();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
}

aop的配置类

@Slf4j
@Aspect
@Component
public class ManagerAuthorizeAspect {
    @Autowired
    private StringRedisTemplate redisTemplate;

    // @Pointcut("execution(public * com.wangzhou.controller.Manager*.*(..))"+"&& !execution(public * com.wangzhou.controller.ManagerController.*(..))")
    //可以排除同名的
    @Pointcut("execution(public * com.wangzhou.controller.UserController.*(..))")
    public void verify() {
    }

    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("request" + request.getContextPath());
        //查询cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);

        if (cookie == null) {
            log.warn("【登录校验】Cookie中查不到token");
            throw new ManagerAuthorizeException();
        }
        //去redis里查
        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) {
            log.warn("【登录校验】Redis中查不到token");
            throw new ManagerAuthorizeException();
        }
    }

    @Before("execution(public * com.wangzhou.controller.ManagerController.*(..))")
    public void doVer() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        System.out.println("request" + request.getContextPath());
        //查询cookie
        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
       // String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
        if (cookie== null) {

        }else {
            log.warn("【用户已登录过】,无需填写账号密码");
            throw new LoginAuthorizeException();
        }
    }
}

成功后若是未通过登录界面进行用户密码登录,而是直接访问主界面,会自动返回登录界面

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值