Springboot中使用Filter實(shí)現(xiàn)Header認(rè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)文章
java文件復(fù)制代碼片斷(java實(shí)現(xiàn)文件拷貝)
本文介紹java實(shí)現(xiàn)文件拷貝的代碼片斷,大家可以直接放到程序里運(yùn)行2014-01-01使用SpringBoot設(shè)置虛擬路徑映射絕對(duì)路徑
這篇文章主要介紹了使用SpringBoot設(shè)置虛擬路徑映射絕對(duì)路徑的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08SpringBoot項(xiàng)目中jar發(fā)布獲取jar包所在目錄路徑的最佳方法
在開發(fā)過程中,我們經(jīng)常要遇到上傳圖片、word、pdf等功能,但是當(dāng)我們把項(xiàng)目打包發(fā)布到服務(wù)器上時(shí),對(duì)應(yīng)的很多存儲(chǔ)路徑的方法就會(huì)失效,下面這篇文章主要給大家介紹了關(guān)于SpringBoot項(xiàng)目中jar發(fā)布獲取jar包所在目錄路徑的相關(guān)資料2022-07-07Spring實(shí)現(xiàn)Quartz自動(dòng)配置的方法詳解
這篇文章主要介紹了Spring實(shí)現(xiàn)Quartz自動(dòng)配置的方法詳解,如果想在應(yīng)用中使用Quartz任務(wù)調(diào)度功能,可以通過Spring Boot實(shí)現(xiàn)Quartz的自動(dòng)配置,以下介紹如何開啟Quartz自動(dòng)配置,以及Quartz自動(dòng)配置的實(shí)現(xiàn)過程,需要的朋友可以參考下2023-11-11SpringBoot中實(shí)現(xiàn)定時(shí)任務(wù)的4種方式詳解
這篇文章主要介紹了SpringBoot中實(shí)現(xiàn)定時(shí)任務(wù)的4種方式詳解,在Springboot中定時(shí)任務(wù)是一項(xiàng)經(jīng)常能用到的功能,實(shí)現(xiàn)定時(shí)任務(wù)的方式有很多,今天來介紹常用的幾種,需要的朋友可以參考下2023-11-11web.xml詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章給大家詳細(xì)介紹了web.xml的相關(guān)知識(shí),需要的朋友可以參考下2017-07-07MyBatis基礎(chǔ)支持DataSource實(shí)現(xiàn)源碼解析
這篇文章主要為大家介紹了MyBatis基礎(chǔ)支持DataSource實(shí)現(xiàn)源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02SpringBoot項(xiàng)目接收前端參數(shù)的11種方式
在前后端項(xiàng)目交互中,前端傳遞的數(shù)據(jù)可以通過HTTP請(qǐng)求發(fā)送到后端, 后端在Spring Boot中如何接收各種復(fù)雜的前端數(shù)據(jù)呢?這篇文章總結(jié)了11種在Spring Boot中接收前端數(shù)據(jù)的方式,需要的朋友可以參考下2024-12-12