In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to achieve general Auth authentication in Spring Boot". In daily operation, I believe many people have doubts about how to achieve general Auth authentication in Spring Boot. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to achieve general Auth authentication in Spring Boot". Next, please follow the editor to study!
I. Preface
This web framework is implemented by the department forerunner based on spring-boot, which lies between the business and the Spring framework. It does some general functions that tend to the business, such as log output, function switch, general parameter parsing and so on. Usually transparent to the business, recently I have been busy doing the requirements well, writing the code well, and never even noticing its existence.
II. Traditional AOP
For this requirement, the first thing that comes to mind is, of course, the AOP interface provided by Spring-boot. You only need to add the pointcut before the Controller method, and then deal with the pointcut.
Realize
The steps for its use are as follows:
Declare the facet class WhitelistAspect using @ Aspect
Add a pointcut whitelistPointcut () to the pointcut class. In order to achieve the ability to assemble pointcuts flexibly, instead of using execution to intercept all the pointcuts, add an annotation @ Whitelist, and the annotated method will verify the whitelist.
Use the spring AOP annotation @ Before in the aspect class to declare a notification method checkWhitelist () to verify the whitelist before the Controller method is executed.
The pseudo code of the section class is as follows:
@ Aspectpublic class WhitelistAspect {@ Before (value = "whitelistPointcut () & & @ annotation (whitelist)") public void checkAppkeyWhitelist (JoinPoint joinPoint, Whitelist whitelist) {checkWhitelist (); / / you can use joinPoint.getArgs () to obtain the parameters of the Controller method / / you can use the whitelist variable to obtain the annotation parameter} @ Pointcut ("@ annotation (com.zhenbianshu.Whitelist)") public void whitelistPointCut () {}}
Add @ Whitelist annotation to the Controller method to implement the function.
III. Interceptor
Spring's interceptor (Interceptor) is also very appropriate to implement this function. As the name implies, the interceptor is used to determine whether to execute this method by some parameters before the Action is executed in the Controller. To implement an interceptor, you can implement the HandlerInterceptor interface of Spring.
Realize
The implementation steps are as follows:
Define the interceptor class AppkeyInterceptor class and implement the HandlerInterceptor interface.
Implement its preHandle () method
Determine whether a request needs to be intercepted by annotations and parameters in the preHandle method. When intercepting a request, the API returns false
Register this interceptor in a custom WebMvcConfigurerAdapter class
The AppkeyInterceptor class is as follows:
@ Componentpublic class WhitelistInterceptor implements HandlerInterceptor {@ Overridepublic boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {Whitelist whitelist = ((HandlerMethod) handler) .getMethodAnnotation (Whitelist.class); / / whitelist.values (); get the request parameter through request, and the annotation parameter return true through the whitelist variable } @ Overridepublic void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {/ / method executes} @ Overridepublic void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {/ / after view view rendering is completed.
To enable the interceptor, you need to explicitly configure it to enable, and here we configure it using WebMvcConfigurerAdapter. It should be noted that the MvcConfiguration that inherits it needs to be under the ComponentScan path.
@ Configurationpublic class MvcConfiguration extends WebMvcConfigurerAdapter {@ Overridepublic void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (new WhitelistInterceptor ()). AddPathPatterns ("/ *"). Order (1); / / you can configure the order of path enabled by the interceptor. When there are multiple interceptors, any interceptor returning false will prevent subsequent request methods from executing}}
It is also important to note that the response code after successful execution of the interceptor is 200, but the response data is empty.
After using the interceptor to implement the function, the leader finally came up with a big trick: we already have an Auth parameter, and appkey can be taken from the Auth parameter, which can be used as a way of Auth when it is not on the whitelist. Why not check it during Auth? Emmm... Vomiting blood.
IV. ArgumentResolver
The parameter parser is a tool provided by Spring for parsing custom parameters. Our commonly used @ RequestParam annotation has its shadow, and with it, we can combine the parameters into what we want before entering the Controller Action.
Spring maintains a ResolverList, and when the request arrives, Spring finds that there are custom type parameters (non-primitive types) and tries these Resolver in turn until a Resolver can parse the required parameters. To implement a parameter parser, you need to implement the HandlerMethodArgumentResolver interface.
Realize
Define a custom parameter type, AuthParam, with appkey related fields in the class
Define AuthParamResolver and implement HandlerMethodArgumentResolver interface
Implement the supportsParameter () interface method to adapt AuthParam to AuthParamResolver
Implement the resolveArgument () interface method to parse the reqest object and generate the AuthParam object, and verify the AuthParam here to confirm whether the appkey is in the whitelist
Add the AuthParam parameter to the signature of the Controller Action method to enable this Resolver
The AuthParamResolver classes that are implemented are as follows
@ Componentpublic class AuthParamResolver implements HandlerMethodArgumentResolver {@ Overridepublic boolean supportsParameter (MethodParameter parameter) {return parameter.getParameterType (). Equals (AuthParam.class);} @ Overridepublic Object resolveArgument (MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {Whitelist whitelist = parameter.getMethodAnnotation (Whitelist.class); / / check whitelist return new AuthParam () through webRequest and whitelist;}} expand
Of course, using the parameter parser also needs to be configured separately, and we also configure it within WebMvcConfigurerAdapter:
Configurationpublic class MvcConfiguration extends WebMvcConfigurerAdapter {@ Overridepublic void addArgumentResolvers (List argumentResolvers) {argumentResolvers.add (new AuthParamResolver ());}}
After this implementation, I was still a little worried, so I looked on the Internet to see if there were other ways to achieve this function, and found that Filter was common.
IV. Filter
Filter is not provided by Spring, it is defined in the Servlet specification and is supported by the Servlet container. Requests filtered by Filter are not dispatched to the Spring container. Its implementation is also relatively simple, just implement the javax.servlet.Filter interface.
Because it is not in the Spring container, Filter cannot get the resources of the Spring container, so you can only use the ServletRequest and ServletResponse of the native Java to obtain the request parameters.
In addition, the doFilter method that calls FilterChain should be displayed in a Filter, otherwise the request is considered to be intercepted. The implementation is similar to:
Public class WhitelistFilter implements javax.servlet.Filter {@ Overridepublic void init (FilterConfig filterConfig) throws ServletException {/ / is called once after initialization} @ Overridepublic void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, and ServletException {/ / determines whether to intercept chain.doFilter (request, response) / / request to expand Filter by calling} @ Overridepublic void destroy () {/ / once when destroyed}} also needs display configuration: @ Configurationpublic class FilterConfiguration {@ Beanpublic FilterRegistrationBean someFilterRegistration () {FilterRegistrationBean registration = new FilterRegistrationBean (); registration.setFilter (new WhitelistFilter ()); registration.addUrlPatterns ("/ *"); registration.setName ("whitelistFilter"); registration.setOrder (1); / / sets the order in which the filter is called return registration }} at this point, the study on "how to achieve general Auth certification by Spring Boot" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.