JWT与自定义注解

JWT

JWTUtil

package com.example.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;

@Service
public class JWTUtils {
    //token需要有一个过期时间
    public static final long TOKEN_EXPIRE = 60 * 1000 * 1000;
    //token的生成需要一个加密的密钥
    public static final String TOKEN_SECRET = "194ce5d0b89c47ff6b30bfb491f9dc26";

    public static void main(String[] args) {
        //        String nihao = DigestUtils.md5DigestAsHex("nihao".getBytes());
        //        System.out.println(nihao);
//        String token = generateToken("1");
//        System.out.println(verifyToken(token));
//        System.out.println(getClaim(token));
    }

    //生成并发放给用户一个token
    public  String generateToken(String id) {
        //过期时间的计算
        Date date = new Date(System.currentTimeMillis() + TOKEN_EXPIRE);
        //设置一个算法
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET.getBytes());
        //设置一个header
        HashMap<String, Object> header = new HashMap<String, Object>();
        header.put("alg", "HMAC256");
        header.put("type", "JWT");
        String token = JWT.create().withHeader(header).withClaim("id", id).withExpiresAt(date).sign(algorithm);
        return token;
    }

    //验证token是否正确
    public  boolean verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET.getBytes());
            DecodedJWT verify = JWT.require(algorithm).build().verify(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //从token中解答出我们加密的信息
    public  String getClaim(String token) {
        DecodedJWT decode = JWT.decode(token);
        Claim id = decode.getClaim("id");
//        Claim info = decode.getClaim("info");
//        System.out.println(Arrays.toString(info.asArray(String.class)));
        return id.asString();
    }
}

自定义注解

package com.example.annotaion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoginUser {
}

package com.example.annotaion;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.PARAMETER})
public @interface Token {
    String value() default "";
}

配置resolver

package com.example.resolver;

import com.example.annotaion.Token;
import com.example.entity.User;
import com.example.util.JWTUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.annotation.Resource;

public class TokenResolver implements HandlerMethodArgumentResolver {
    @Resource
    JWTUtils jwtUtils;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(String.class)&&methodParameter.hasParameterAnnotation(Token.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        String token = nativeWebRequest.getParameter("token");
        boolean b = jwtUtils.verifyToken(token);
        if (b){
            String id = jwtUtils.getClaim(token);
            //数据库操作
            return new User(10,23,"silk");
        }
        return null;
    }
}
package com.example.config;

import com.example.annotaion.Token;
import com.example.resolver.TokenResolver;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
class MyConfig implements WebMvcConfigurer {
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new TokenResolver());
    }

    //    @Override
    //    public void addInterceptors(InterceptorRegistry registry) {
    //        registry.addInterceptor()
    //    }
}

实体类

package com.example.entity;

import lombok.Data;

@Data
public class User {
    int id;
    int age;
    String name;

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }
}

controller

package com.example.controller;

import com.example.annotaion.LoginUser;
import com.example.annotaion.Token;
import com.example.entity.User;
import com.example.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Token("class token")
public class HelloController {
    @Resource
    JWTUtils jwtUtils;

    @RequestMapping("/login/{id}")
    public Map login(@PathVariable String id) {
        String token = jwtUtils.generateToken(id);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("token", token);
        return map;
    }

    @RequestMapping("pay")
    @Token("methdo token")
    public Map pay(@Token User User) {
        //常规的做法
        //验证token//
        //解析出用户id
        //权限校验
        //这种实现好吗
//        String token = request.getParameter("token");
//        boolean b = jwtUtils.verifyToken(token);
//        String id = null;
//        if (b) {
//            id = jwtUtils.getClaim(token);
//        }
        System.out.println("id");
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("id", "20");
        return map;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

micro_cloud_fly

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值