当前位置:   article > 正文

接口鉴权方案 jwt_jwt接口鉴权

jwt接口鉴权
  1. 引入依赖

    io.jsonwebtoken
    jjwt-api
    0.10.7


    io.jsonwebtoken
    jjwt-impl
    0.10.7
    runtime


    io.jsonwebtoken
    jjwt-jackson
    0.10.7
    runtime

    2.TokenUtil
    public class TokenUtil {

/**

  • key(按照签名算法的字节长度设置key)
    */

    private final static String SECRET_KEY = “0123456789_0123456789_0123456789”;

    private final static long TOKEN_EXPIRE_MILLIS = 1000 * 60 * 20;

/**

  • 创建token

  • @param claimMap

  • @return
    */

    public static String createToken(Map<String, Object> claimMap) {
    long currentTimeMillis = System.currentTimeMillis();
    return Jwts.builder()
    .setId(UUID.randomUUID().toString())
    .setIssuedAt(new Date(currentTimeMillis)) // 设置签发时间
    .setExpiration(new Date(currentTimeMillis + TOKEN_EXPIRE_MILLIS)) // 设置过期时间
    .addClaims(claimMap)
    .signWith(generateKey())
    .compact();
    }

/**

  • 验证token

  • @param token

  • @return 0 验证成功,1、2、3、4、5 验证失败
    */

    public static int verifyToken(String token) {
    try {
    Jwts.parser().setSigningKey(generateKey()).parseClaimsJws(token);
    return 0;
    } catch (ExpiredJwtException e) {
    e.printStackTrace();
    return 1;
    } catch (UnsupportedJwtException e) {
    e.printStackTrace();
    return 2;
    } catch (MalformedJwtException e) {
    e.printStackTrace();
    return 3;
    } catch (SignatureException e) {
    e.printStackTrace();
    return 4;
    } catch (IllegalArgumentException e) {
    e.printStackTrace();
    return 5;
    }
    }

/**

  • 解析token

  • @param token

  • @return
    */

    public static Map<String, Object> parseToken(String token) {
    return Jwts.parser() // 得到DefaultJwtParser
    .setSigningKey(generateKey()) // 设置签名密钥
    .parseClaimsJws(token)
    .getBody();
    }

/**

  • 生成安全密钥

  • @return
    */

    public static Key generateKey() {
    return new SecretKeySpec(SECRET_KEY.getBytes(), SignatureAlgorithm.HS256.getJcaName());
    }

}

3.鉴权注解

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})

public @interface Authentication {
}

4.鉴权切面
@Slf4j
@Aspect
@Component
public class AuthenticationAop {
@Pointcut(“@annotation( com.sohu.mptvad.equipment_monitoring.annotation.Authentication)”)
public void pointCutMethodBefore() {
}

@Before("pointCutMethodBefore()")
public void doBefore(JoinPoint point) throws Exception {
    MethodInvocationProceedingJoinPoint mjp = (MethodInvocationProceedingJoinPoint) point;
    MethodSignature signature = (MethodSignature) mjp.getSignature();
    Method method = signature.getMethod();
    Authentication annotation = method.getAnnotation(Authentication.class);
    if (annotation != null) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if (request ==null) {
            throw new AuthenticationException("【鉴权失败】,获取HttpServletRequest");
        }
        String token = request.getParameter("token");
        if (StringUtils.isEmpty(token)) {

            throw new AuthenticationException("【鉴权失败】,token不存在");
        }
        Integer verifyToken = TokenUtil.verifyToken(token);

        if (verifyToken == 1) {
            throw new AuthenticationException("【鉴权失败】,token已过期");
        }
        if (verifyToken != 0) {
            throw new AuthenticationException("【鉴权失败】,token错误");
        }
    }
}
@AfterThrowing(value = "@annotation( com.sohu.mptvad.equipment_monitoring.annotation.Authentication)",throwing = "ex")
public void handleException(Exception  ex) {
    log.error(ex.getMessage());
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

}
5.使用注解在接口上

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/989912
推荐阅读
相关标签
  

闽ICP备14008679号