Spring Boot 實(shí)現(xiàn)通用 Auth 認(rèn)證的 4 種方式
點(diǎn)擊下方“IT牧場”,選擇“設(shè)為星標(biāo)”

| 前言
通用的 appkey 白名單校驗(yàn)功能,希望它的擴(kuò)展性更好一些。| 傳統(tǒng)AOP
實(shí)現(xiàn)
使用 @Aspect聲明一下切面類WhitelistAspect;在切面類內(nèi)添加一個切點(diǎn) whitelistPointcut(),為了實(shí)現(xiàn)此切點(diǎn)靈活可裝配的能力,這里不使用execution全部攔截,而是添加一個注解@Whitelist,被注解的方法才會校驗(yàn)白名單。在切面類中使用 spring 的 AOP 注解 @Before聲明一個通知方法checkWhitelist()在 Controller 方法被執(zhí)行之前校驗(yàn)白名單。
public class WhitelistAspect {(value = "whitelistPointcut() && @annotation(whitelist)")public void checkAppkeyWhitelist(JoinPoint joinPoint, Whitelist whitelist) {checkWhitelist();// 可使用 joinPoint.getArgs() 獲取Controller方法的參數(shù)// 可以使用 whitelist 變量獲取注解參數(shù)}("@annotation(com.zhenbianshu.Whitelist)")public void whitelistPointCut() {}}
@Whitelist 注解實(shí)現(xiàn)功能。擴(kuò)展
uid() 等方法,實(shí)現(xiàn)自定義校驗(yàn)。execution(執(zhí)行方法) 、bean(匹配特定名稱的 Bean 對象的執(zhí)行方法)等切點(diǎn)聲明方法和 @Around(在目標(biāo)函數(shù)執(zhí)行中執(zhí)行) 、@After(方法執(zhí)行后) 等通知方法。| Interceptor
HandlerInterceptor 接口。實(shí)現(xiàn)
定義攔截器類 AppkeyInterceptor類并實(shí)現(xiàn) HandlerInterceptor 接口。實(shí)現(xiàn)其 preHandle()方法;在 preHandle 方法內(nèi)通過注解和參數(shù)判斷是否需要攔截請求,攔截請求時接口返回 false;在自定義的 WebMvcConfigurerAdapter類內(nèi)注冊此攔截器;
AppkeyInterceptor 類如下:public class WhitelistInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Whitelist whitelist = ((HandlerMethod) handler).getMethodAnnotation(Whitelist.class);// whitelist.values(); 通過 request 獲取請求參數(shù),通過 whitelist 變量獲取注解參數(shù)return true;}public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {// 方法在Controller方法執(zhí)行結(jié)束后執(zhí)行}public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {// 在view視圖渲染完成后執(zhí)行}}
WebMvcConfigurerAdapter 對它進(jìn)行配置。需要注意,繼承它的的 MvcConfiguration 需要在 ComponentScan 路徑下。public class MvcConfiguration extends WebMvcConfigurerAdapter {public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(new WhitelistInterceptor()).addPathPatterns("/*").order(1);// 這里可以配置攔截器啟用的 path 的順序,在有多個攔截器存在時,任一攔截器返回 false 都會使后續(xù)的請求方法不再執(zhí)行}}
200,但響應(yīng)數(shù)據(jù)為空。| ArgumentResolver
@RequestParam 注解就有它的影子,使用它,我們可以將參數(shù)在進(jìn)入Controller Action之前就組合成我們想要的樣子。ResolverList, 在請求到達(dá)時,Spring 發(fā)現(xiàn)有自定義類型參數(shù)(非基本類型), 會依次嘗試這些 Resolver,直到有一個 Resolver 能解析需要的參數(shù)。要實(shí)現(xiàn)一個參數(shù)解析器,需要實(shí)現(xiàn) HandlerMethodArgumentResolver 接口。實(shí)現(xiàn)
定義自定義參數(shù)類型
AuthParam,類內(nèi)有 appkey 相關(guān)字段;定義
AuthParamResolver并實(shí)現(xiàn) HandlerMethodArgumentResolver 接口;實(shí)現(xiàn)
supportsParameter()接口方法將 AuthParam 與 AuthParamResolver 適配起來;實(shí)現(xiàn)
resolveArgument()接口方法解析 reqest 對象生成 AuthParam 對象,并在此校驗(yàn) AuthParam ,確認(rèn) appkey 是否在白名單內(nèi);在 Controller Action 方法上簽名內(nèi)添加 AuthParam 參數(shù)以啟用此 Resolver;
public class AuthParamResolver implements HandlerMethodArgumentResolver {public boolean supportsParameter(MethodParameter parameter) {return parameter.getParameterType().equals(AuthParam.class);}public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {Whitelist whitelist = parameter.getMethodAnnotation(Whitelist.class);// 通過 webRequest 和 whitelist 校驗(yàn)白名單return new AuthParam();}}
WebMvcConfigurerAdapter內(nèi)配置:public class MvcConfiguration extends WebMvcConfigurerAdapter {public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {argumentResolvers.add(new AuthParamResolver());}}
Filter。| Filter
javax.servlet.Filter接口即可。public class WhitelistFilter implements javax.servlet.Filter {public void init(FilterConfig filterConfig) throws ServletException {// 初始化后被調(diào)用一次}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {// 判斷是否需要攔截chain.doFilter(request, response); // 請求通過要顯示調(diào)用}public void destroy() {// 被銷毀時調(diào)用一次}}
Filter 也需要顯示配置:
public class FilterConfiguration {public FilterRegistrationBean someFilterRegistration() {FilterRegistrationBean registration = new FilterRegistrationBean();registration.setFilter(new WhitelistFilter());registration.addUrlPatterns("/*");registration.setName("whitelistFilter");registration.setOrder(1); // 設(shè)置過濾器被調(diào)用的順序return registration;}}
| 小結(jié)
如喜歡本文,請點(diǎn)擊右上角,把文章分享到朋友圈
如有想了解學(xué)習(xí)的技術(shù)點(diǎn),請留言給若飛安排分享
·END·
作者:枕邊書
來源:https://zhenbianshu.github.io/2018/06/spring_boot_generic_auth.html
版權(quán)申明:內(nèi)容來源網(wǎng)絡(luò),僅供分享學(xué)習(xí),版權(quán)歸原創(chuàng)者所有。除非無法確認(rèn),我們都會標(biāo)明作者及出處,如有侵權(quán)煩請告知,我們會立即刪除并表示歉意。謝謝!
加個關(guān)注不迷路
喜歡就點(diǎn)個"在看"唄^_^
評論
圖片
表情
