springboot 统一Token校验 --- Filter 过滤器

  作者:记性不好的阁主

1、创建自定义过滤器





package cn.ucmed.privacy.agreement.filter;

import cn.ucmed.privacy.agreement.config.PropertiesConfig;
import cn.ucmed.privacy.agreement.util.ResponseUtil;
import cn.ucmed.privacy.agreement.util.ReturnCode;
import cn.ucmed.yilian.common.model.Response;
import com.alibaba.fastjson.JSON;
import com.ucmed.doctorusercenter.bean.WebReturnData;
import com.ucmed.doctorusercenter.bean.entbean.GetUserInfoParam;
import com.ucmed.doctorusercenter.bean.retbean.LoginUserInfo;
import com.ucmed.doctorusercenter.httpservice.HttpDjUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

@Component
public class TokenFilter implements Filter {

private static Logger LOG = LoggerFactory.getLogger(TokenFilter.class);

private PropertiesConfig propertiesConfig;

@Override
public void init(FilterConfig filterConfig) throws ServletException {
ServletContext context = filterConfig.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
this.propertiesConfig = ctx.getBean(PropertiesConfig.class);
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {


HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse rep = (HttpServletResponse) response;

//设置允许跨域的配置
// 这里填写你允许进行跨域的主机ip(正式上线时可以动态配置具体允许的域名和IP
rep.setHeader("Access-Control-Allow-Origin", "*");
// 允许的访问方法
rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
// Access-Control-Max-Age 用于 CORS 相关配置的缓存
rep.setHeader("Access-Control-Max-Age", "3600");
rep.setHeader("Access-Control-Allow-Headers","token,Origin, X-Requested-With, Content-Type, Accept");



response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
String token = req.getParameter("token");

// token phone 校验
GetUserInfoParam getUserInfoParam = new GetUserInfoParam();
getUserInfoParam.setToken(token);
WebReturnData<LoginUserInfo> webReturnData = HttpDjUserService
.GetUserInfo(getUserInfoParam);
if(webReturnData == null) {
LOG.info("webReturnData == null");
Return(response,ResponseUtil.returnError(ReturnCode.STATE_1002));
return;
}
if(webReturnData.getRet_code() != 0
&& webReturnData.getRet_data() == null) {
LOG.info("webReturnData :{}",
JSON.toJSONString(webReturnData));
Return(response,ResponseUtil.returnError(ReturnCode.STATE_1002));
return;
}
LoginUserInfo loginUserInfo = webReturnData.getRet_data();
if(!propertiesConfig.editPhoneList
.contains(loginUserInfo.getLoginname())) {
Return(response,ResponseUtil.returnError(ReturnCode.STATE_409));
return;
}

filterChain.doFilter(request,response);



}

@Override
public void destroy() {

}

private void Return(ServletResponse response, Response resultInfo) throws IOException {
PrintWriter writer = null;
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(response.getOutputStream(),
"UTF-8");
writer = new PrintWriter(osw, true);
String jsonStr = JSON.toJSONString(resultInfo);
writer.write(jsonStr);
writer.flush();
writer.close();
osw.close();
} catch (UnsupportedEncodingException e) {
LOG.error("过滤器返回信息失败:" + e.getMessage(), e);
} catch (IOException e) {
LOG.error("过滤器返回信息失败:" + e.getMessage(), e);
} finally {
if (null != writer) {
writer.close();
}
if (null != osw) {
osw.close();
}
}
}
}


*  此例中要用要propertiesConfig  (应用到其他项目可忽略,本例需要)


private PropertiesConfig propertiesConfig;


为需要依赖注入的配置类


使用@Autowired会取不到

这里改用在初始化时使用applicationContext去取


@Override
public void init(FilterConfig filterConfig) throws ServletException {
ServletContext context = filterConfig.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
this.propertiesConfig = ctx.getBean(PropertiesConfig.class);
}


====================================================================


重点:获取token参数方式


String token = req.getParameter("token");



====================================================================


由于doFilter为void

所以这里封装了一个返回json报错信息的方法,当验证不通过则返回json报错信息


Response为返回实体类 {code、msg、data......}


private void Return(ServletResponse response, Response resultInfo) throws IOException {
PrintWriter writer = null;
OutputStreamWriter osw = null;
try {
osw = new OutputStreamWriter(response.getOutputStream(),
"UTF-8");
writer = new PrintWriter(osw, true);
String jsonStr = JSON.toJSONString(resultInfo);
writer.write(jsonStr);
writer.flush();
writer.close();
osw.close();
} catch (UnsupportedEncodingException e) {
LOG.error("过滤器返回信息失败:" + e.getMessage(), e);
} catch (IOException e) {
LOG.error("过滤器返回信息失败:" + e.getMessage(), e);
} finally {
if (null != writer) {
writer.close();
}
if (null != osw) {
osw.close();
}
}
}



2、注册过滤器


package cn.ucmed.privacy.agreement;

import cn.ucmed.privacy.agreement.filter.TokenFilter;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

import java.util.ArrayList;
import java.util.List;

@EnableAsync
@Configuration
@EnableApolloConfig({ "application", "petra.center.common" })
@EnableDiscoveryClient
@SpringBootApplication
@EnableScheduling
@MapperScan("cn.ucmed.privacy.agreement.mapper")
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

//注册filter
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TokenFilter tokenFilter = new TokenFilter();
registrationBean.setFilter(tokenFilter);
List<String> urlPatterns = new ArrayList<String>();
urlPatterns.add("/privacy/agreement/*");
registrationBean.setUrlPatterns(urlPatterns);
return registrationBean;
}

}



urlPatterns.add("/privacy/agreement/*");


可以根据接口地址的过滤需要,添加需要过滤的路径



相关推荐

评论 抢沙发

表情

分类选择