spring boot项目
1.定义拦截器(对请求头信息进行鉴权认证)
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
@PropertySource(value = {"classpath:config/authorSetting.properties"})
public class AuthorizationInterceptor implements HandlerInterceptor {
private @Value("#{'${author.sign}'.split(',')}")
List<String> signs;
private @Value("#{'${author.appcode}'.split(',')}")
List<String> appcodes;
public final boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException, IOException {
// log.info("sign====" + sign.toString());
// log.info("appcode====" + appcode.toString());
String reqSign = request.getHeader("sign");
String resAppCode = request.getHeader("appCode");
for (int i = 0; i < appcodes.size(); i++) {
if (signs.get(i).equals(reqSign) && appcodes.get(i).equals(resAppCode)) {
// log.info("鉴权成功!!");
return true;
}
}
handleNotAuthorized(request, response, handler);
return false;
}
protected void handleNotAuthorized(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException, IOException {
// 403表示资源不可用。服务器理解用户的请求,但是拒绝处理它,通常是由于权限的问题
response.sendError(403);
}
}
2.配置类中注册定义的拦截器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebConfig extends WebMvcConfigurerAdapter {
@Autowired
private AuthorizationInterceptor authorizationInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authorizationInterceptor)
.addPathPatterns("/grid/query") //拦截项目中的哪些请求
.addPathPatterns("/beehive/noticeMessage") //拦截项目中的哪些请求
.addPathPatterns("/beehive/pushQueryResult") //拦截项目中的哪些请求
.excludePathPatterns(""); //对项目中的哪些请求不拦截
}
}
认证信息存到这里