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 {
public static final long TOKEN_EXPIRE = 60 * 1000 * 1000;
public static final String TOKEN_SECRET = "194ce5d0b89c47ff6b30bfb491f9dc26";
public static void main(String[] args) {
}
public String generateToken(String id) {
Date date = new Date(System.currentTimeMillis() + TOKEN_EXPIRE);
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET.getBytes());
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;
}
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;
}
public String getClaim(String token) {
DecodedJWT decode = JWT.decode(token);
Claim id = decode.getClaim("id");
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());
}
}
实体类
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) {
System.out.println("id");
HashMap<String, Object> map = new HashMap<>();
map.put("code", 200);
map.put("id", "20");
return map;
}
}