欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot中使用Filter實(shí)現(xiàn)Header認(rèn)證詳解

 更新時(shí)間:2023年08月12日 10:05:38   作者:牛奮lch  
這篇文章主要介紹了Springboot中使用Filter實(shí)現(xiàn)Header認(rèn)證詳解,當(dāng)在?web.xml?注冊(cè)了一個(gè)?Filter?來對(duì)某個(gè)?Servlet?程序進(jìn)行攔截處理時(shí),它可以決定是否將請(qǐng)求繼續(xù)傳遞給?Servlet?程序,以及對(duì)請(qǐng)求和響應(yīng)消息是否進(jìn)行修改,需要的朋友可以參考下

前言

假設(shè)客戶端在http請(qǐng)求中,已經(jīng)加入了Header的認(rèn)證信息,例如:

HttpPost post = new HttpPost("http://localhost:8990/sendMail");
				StringEntity entity = new StringEntity(json, "utf-8");
				entity.setContentType("application/json");
				post.setEntity(entity);
				// 設(shè)置驗(yàn)證頭信息
				post.addHeader("token", "WEFGYHJIKLTY4RE6DF29HNBCFD13ER87");

那么服務(wù)端怎么通過Filter,來驗(yàn)證客戶端的token是否有效了?請(qǐng)接著往下看。

一、實(shí)現(xiàn)自定義Filter

1、實(shí)現(xiàn)Filter接口

我們要自定義Filter,只需實(shí)現(xiàn)Filter接口即可

2、覆寫doFilter方法

根據(jù)業(yè)務(wù)邏輯,來覆寫doFilter方法

示例如下:

@Slf4j
@Component
@WebFilter(urlPatterns={"/sendMail/*"}, filterName="tokenAuthorFilter")
public class TokenAuthorFilter implements Filter {
	@Autowired
	private AuthorizationRepository repository;
	@Override
	public void destroy() {
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		String token = req.getHeader("token");
		Response res = new Response();
		boolean isFilter = false;
		if (null == token || token.isEmpty()) {
			res.setSuccess(false);
			res.setErrorCode("403");
			res.setErrorMessage("token沒有認(rèn)證通過!原因?yàn)椋嚎蛻舳苏?qǐng)求參數(shù)中無token信息");
		} else {
			Authorization auth = repository.findByToken(token);
			if (null == auth) {
				res.setSuccess(false);
				res.setErrorCode("403");
				res.setErrorMessage("token沒有認(rèn)證通過!原因?yàn)椋嚎蛻舳苏?qǐng)求中認(rèn)證的token信息無效,請(qǐng)查看申請(qǐng)流程中的正確token信息");
			}else if((auth.getStatus() == 0)){
				res.setSuccess(false);
				res.setErrorCode("401");
				res.setErrorMessage("該token目前已處于停用狀態(tài),請(qǐng)聯(lián)系郵件系統(tǒng)管理員確認(rèn)!");
			}else{
				isFilter = true;
				res.setSuccess(true);
			}
		}
		if(!res.isSuccess()){
			PrintWriter writer = null;
			OutputStreamWriter osw = null;
			try {
				osw = new OutputStreamWriter(response.getOutputStream() , "UTF-8");
				writer = new PrintWriter(osw, true);
				String jsonStr = ObjectMapperInstance.getInstance().writeValueAsString(res);
				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();
				}
			}
			return;
		}
		if(isFilter){
			log.info("token filter過濾ok!");
			chain.doFilter(request, response);
		}
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
}

通過上面的幾步,就實(shí)現(xiàn)了一個(gè)自定義的Filter。

3、注冊(cè)Filter

接下來,需要注冊(cè)這個(gè)過濾器,spring boot提供了以下兩種注冊(cè)方式。

3.1 是用注解注冊(cè)

在Filter上添加如下注解即可

@Slf4j
@Component
@WebFilter(urlPatterns={"/sendMail/*"}, filterName="tokenAuthorFilter")
public class TokenAuthorFilter implements Filter {

@WebFilter注解的作用就是用來注冊(cè)Filter,通過這種方式注冊(cè)的Filter,需要在啟動(dòng)類上加上@ServletComponentScan注解才能生效,如下:

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

3.2 手動(dòng)配置Filter

@Configuration
@Component
public class FilterConfig {
	@Autowired
	private TokenAuthorFilter filter;
	@Bean
    public FilterRegistrationBean  filterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        List<String> urlPatterns = new ArrayList<String>();
        urlPatterns.add("/sendMail/*");// 設(shè)置匹配的url
        registrationBean.setUrlPatterns(urlPatterns);
        return registrationBean;
    }
}

上面兩種方式雖然使用上有些不一樣,但是本質(zhì)都是一樣的,都會(huì)調(diào)用FilterRegistrationBean來進(jìn)行注冊(cè)。

二、spring boot內(nèi)置的Filter

為了方便我們的開發(fā),spring boot內(nèi)置了許多有用的Filter,我們可以根據(jù)業(yè)務(wù)的需求,選擇適合業(yè)務(wù)的Filter。

三、拓展

通過前面的N篇博客,我們會(huì)發(fā)現(xiàn)spring boot處理Servlet,Listener,F(xiàn)ilter的思路大致都是一樣

對(duì)應(yīng)的注解分別為@WebServlet 、@WebListener、@WebFilter

對(duì)應(yīng)的注冊(cè)Bean分別為ServletRegistrationBean,ServletListenerRegistrationBean,FilterRegistrationBean

無論哪種方式,都大大的簡(jiǎn)化了我們的開發(fā)

到此這篇關(guān)于Springboot中使用Filter實(shí)現(xiàn)Header認(rèn)證詳解的文章就介紹到這了,更多相關(guān)Filter實(shí)現(xiàn)Header認(rèn)證內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論