实现 根据用户 tokin 将对应的id注入到controller 指定参数中
springboot引入
类 WebMvcConfig 继承 WebMvcConfigurerAdapter 实际上是实现了springboot WebMvcConfigurer接口
即可调用自定义的 AuthResolver 方法对参数进行二次封装
package com.bootdo.common.config;
import com.bootdo.common.infrastructure.AuthResolver;
import org.springframework.beans.factory.annotation.Autowired;
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.WebMvcConfigurerAdapter;
import java.util.List;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Autowired
private AuthResolver authResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(authResolver);
}
public void addInterceptors(InterceptorRegistry registry) {
}
}
package com.bootdo.common.infrastructure;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.service.UserService;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver;
@Component
public class AuthResolver extends AbstractNamedValueMethodArgumentResolver {
private final Log logger = LogFactory.getLog(this.getClass());
/* @Autowired
private JwtTokenUtil jwtTokenUtil;*/
@Autowired
private UserService userService;
@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
return new NamedValueInfo("userId", false, null);
}
@Override
protected Object resolveName(String name, MethodParameter parameter, NativeWebRequest request) throws Exception {
String authToken = request.getHeader("token");
if (authToken != null && authToken.startsWith("Bearer ")) {
authToken = authToken.substring(7);
}
if (StringUtils.isNotBlank(authToken)) {
try {
用户校验代码
} catch (IllegalArgumentException e) {
// logger.error("an error occured during getting username from token", e);
} catch (ExpiredJwtException e) {
// logger.warn("the token is expired and not valid anymore", e);
}
}
return null;
}
@Override
public boolean supportsParameter(MethodParameter parameter) {
if (parameter.getParameterName().equals("userId")) {
return true;
}
return false;
}
}