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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| package cn.gloduck.gmall.token;
import cn.gloduck.gmall.constant.TokenConstant; import cn.gloduck.gmall.token.annotation.TokenAttribute; import cn.gloduck.gmall.service.TokenService; import cn.gloduck.gmall.token.exception.TokenAttributeException; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; import org.springframework.util.Assert; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;
import javax.servlet.ServletException; import java.util.Map;
@Slf4j public class TokenAttributeMethodArgumentResolver extends AbstractNamedValueMethodArgumentResolver { public TokenAttributeMethodArgumentResolver(TokenService tokenService) { log.info("注入:{}到:{}",tokenService.getClass().getName(), this.getClass().getName()); this.tokenService = tokenService; }
private TokenService tokenService;
@Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.hasParameterAnnotation(TokenAttribute.class); }
@Override protected NamedValueInfo createNamedValueInfo(MethodParameter methodParameter) { TokenAttribute annotation = methodParameter.getParameterAnnotation(TokenAttribute.class); Assert.state(annotation != null, "No RequestAttribute annotation"); return new NamedValueInfo(annotation.name(), annotation.required(), null); }
@Override protected Object resolveName(String s, MethodParameter methodParameter, NativeWebRequest request) throws Exception { String token = request.getHeader(TokenConstant.TOKEN_HEADER); if(token == null){ return null; } TokenAttribute tokenAttribute = methodParameter.getParameterAnnotation(TokenAttribute.class); String group = tokenAttribute.group(); String name = tokenAttribute.name(); Map<String, String> map = tokenService.verifyAndGetPayloadMap(group, token); if(map == null){ return null; } String value = map.get(name); return value; }
@Override protected void handleMissingValue(String name, MethodParameter parameter) throws ServletException { throw new TokenAttributeException(String.format("token中获取参数:%s失败",name)); }
}
|