SpringBoot AOP切面 + Redis 身份验证

一个成熟的项目中,如果有些方法是对登录身份有所限制的话,我们往往回去验证一下用户的身份,方法很简单,就是从Cookie里取出我们的身份信息,再判断是否有效

我们这里使用的身份验证工具时 Redis,我们在用户登录时为用户生成一个 token,把 token 放进 Cookie 传到前端的同时也在Redis 里保存 token

1.创建一个 Redis 用的属性类,如有效期,前缀等

/**
 * @author: 林之谦
 * @date: 2018/8/2
 * @description:
 */

public interface RedisConstant {

    String TOKEN_PREFIX = "token_";

    Integer EXPIRE = 7200; // 2小时

}

2.在 login 方法里生成 token ,往 Cookie 和 Redis 里保存 token

    @GetMapping("/login")
    public ModelAndView login(@RequestParam("openid") String openid,
                              HttpServletResponse response,
                              Map<String,Object> map){
        // 1.openid 去和数据库里的数据匹配
        SellerInfo sellerInfo = sellerService.findSellerByOpenid(openid);
        if(sellerInfo == null){
            map.put("msg",ResultEnum.LOGIN_FAIL.getMsg());
            map.put("url","/sell/seller/order/list");
            return new ModelAndView("common/error");
        }
        // 2.设置token 至redis
        String token = UUID.randomUUID().toString();
        Integer expire = RedisConstant.EXPIRE;
        System.out.println("token = "+token);
        redisTemplate.opsForValue().set(String.format(RedisConstant.TOKEN_PREFIX + token),openid,expire, TimeUnit.SECONDS);
        // 3.设置token 至cookie
        CookieUtil.set(response,CookieConstant.TOKEN,token,expire);
        return new ModelAndView("redirect:" + projectUrlConfig.getSell() + "/sell/seller/order/list");
    }

这里 redis的set方法分别传入 key(key就是生成的 token ),value ( 用户的 id 等可用于辨别身份的数据 ),有效时间

TimeUnit.SECONDS 告诉 Redis 计算时间的单位

3.在 logout 方法里要清除 Redis 和 Cookie

    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request,
                       HttpServletResponse response,
                       Map<String,Object>map){
        // 1.从cookie里查token
        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
            CookieUtil.set(response,CookieConstant.TOKEN,null,0);
        }
        map.put("msg",ResultEnum.LOGOUT_SUCCESS.getMsg());
        map.put("url","/sell/seller/order/list");
        return new ModelAndView("common/success",map);

    }

上面讲了设置身份,那么我们怎么做身份验证呢?需要身份验证的方法很多的时候,我们不能在每个方法里都去手动做一次身份验证,很明显这里身份验证是应该可以封装共享的

我们使用 AOP 切面技术来实现

第一步:建立切点,里面 execution 里对方法进行过滤,意思是 pers.lyt.sell.controller.Seller 为前缀的包下的所有类里所有的public方法,但是不包括 SellerUserController 里的方法,那么这个切点就对上面过滤出来的所有方法有效, 下面的方法verify()就代表了所有要被切的方法

    @Pointcut("execution(public * pers.lyt.sell.controller.Seller*.*(..))" +
    "&& !execution(public * pers.lyt.sell.controller.SellerUserController.*(..))")
    public void verify() {
    }

第二步:编写切面方法,@Before注解 下的方法会在切点方法执行前执行,这个就最适合身份验证

@Before("verify()")
public void doVerify(){
    ...
}

完整的 AOP 类如下

/**
 * 卖家授权切面
 * @author: 林之谦
 * @date: 2018/8/2
 * @description:
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Pointcut("execution(public * pers.lyt.sell.controller.Seller*.*(..))" +
    "&& !execution(public * pers.lyt.sell.controller.SellerUserController.*(..))")
    public void verify() {
    }

    @Before("verify()")
    public void doVerify(){
        // 获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //查询cookie
        Cookie cookie = CookieUtil.get(request,CookieConstant.TOKEN);
        if(cookie == null){
            log.warn("【登陆校验】 Cookie中查不到token");
            throw new SellerAuthorizeException();
        }

        String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX+cookie.getValue()));
        if(StringUtils.isEmpty(tokenValue)){
            log.warn("【登陆校验】 Redis中查不到token");
            throw new SellerAuthorizeException();
        }
    }
}

那么在被切的所有方法执行前都会只想上面的登录校验了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值