AOP + 注解实现登录判断

对于一个小白来说,就比如我,之前学习spring 的aop,属实是有点蒙圈,不知道这玩意能干嘛,记录日志这是我唯一想到的,然后就是注解的运用,也是一知半解。

在前几个项目中,我的登录判断都是通过全局配置,判断请求中是否有token,这样虽好,但是也不好,因为把一些不必要的接口也做了登录判断,后面也是在一些博客中看到了注解的方式实现登录判断,这里就记录一下

首先是定义一个注解:Login

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Login {
// 这里我是使用的CLIENT和ADMIN来作为权限符的,也可以自己换一下
	String issuer() default "CLIENT";
}

然后就是通过AOP去对注解进行判断

import com.cl.blog.annotation.Login;
import com.cl.blog.common.Const;
import com.cl.blog.exception.WebException;
import com.cl.blog.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

	@Resource
	JwtUtil jwtUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Login annotation;
		// 判断当前请求是否为方法,如果是,就对其进行注解判断
		if (handler instanceof HandlerMethod) {
			annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
		} else {
			return true;
		}

		if (annotation == null) {
			return true;
		}

		String token = request.getHeader("token");
		String issuer = annotation.issuer();
		System.out.println("--->"+token);
		// 判断token是否合法
		if (!StringUtils.hasText(token)) {
			throw new WebException("请先登录");
		}
		if (!StringUtils.hasText(issuer)) {
			throw new WebException("请先登录");
		}

		// 判断token内容是否存在,且是否超时
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_USER);
		if (claim == null) {
			claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);
		}
		if (claim == null || jwtUtil.isTokenExpired(claim.getExpiration())) {
			throw new WebException("请先登录");
		}
		if (!annotation.issuer().equals(claim.getIssuer()) && (annotation.issuer().equals(Const.GRADE_ADMIN))) {
			throw new WebException("抱歉,权限不足");
		}

		// 将用户信息存储到session
		request.getSession().setAttribute(Const.USER_KEY, Long.parseLong(claim.getSubject()));
		return true;
	}
}

当然,我这里也做了一个权限的判断,例如哪些是客户端能访问的,也就是普通用户访问的,哪些是管理员登录访问的,当然有些接口可以共用,就可以把参数改为数组的形式,这里就不做修改了

这里还用到了一个工具类,我也贴出来了

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Date;

@Slf4j
@Data
@Component
@ConfigurationProperties("jwt")
public class JwtUtil {
	private String secret;
	private long expire;

	/**
	 * 生成token
	 */
	public  String generateToken(long userId,String issuer){
		Date date = new Date();
		// 过期时间
		Date expireDate = new Date(date.getTime() + expire * 1000);
		return Jwts.builder()
				.setHeaderParam("typ","JWT")
				.setSubject(userId + "")
				.setIssuedAt(date)
				.setIssuer(issuer)
				.setExpiration(expireDate)
				.signWith(SignatureAlgorithm.HS512,secret)
				.compact();
	}

	/**
	 * 解析token
	 * @param token
	 * @return
	 */
	public Claims getClaimByToken(String token,String issuer){
		try {
			Claims claims = Jwts.parser()
					.setSigningKey(secret)
					.parseClaimsJws(token)
					.getBody();
			if (!issuer.equals(claims.getIssuer())|| issuer==null) {
				return null;
			}
			return claims;
		}catch (Exception e){
			log.debug("validDate is token error------>" + e);
			return  null;
		}
	}

	/**
	 * 判断token是否过期
	 * @param expiration
	 * @return true 过期
	 */
	public boolean isTokenExpired(Date expiration){
		return expiration.before(new Date());
	}
}

今天分享就这些了!!!

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值