Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the ways to authenticate SpringBoot projects?

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the ways of SpringBoot project authentication?". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Preface

Recently, I have been overwhelmed by endless business needs and have no time to catch my breath. I finally received a job that allowed me to break through the code comfort zone. The process of solving it was very tortuous, which once made me doubt my life, but the gain was also great, and the code was not obvious, but I felt that I had erased a layer of yarn that java, Tomcat, and Spring had been blocking in front of me. The understanding of them has reached a new level. There is no output for a long time, so pick an aspect to sum up, hoping to understand some other things in the carding process.

Because of the prosperous ecology of Java, there are a large number of articles devoted to each of the following modules. So I chose another point of view, starting from the practical problems, to connect these scattered knowledge together, you can look at it as an overview. For the ultimate detailed introduction of each module, you can look through the official documents or read other blogs on the Internet. The requirements are simple and clear, which is not the same as the flirtatious requirements mentioned by the products: add a general appkey whitelist verification function to our web framework in the hope that it will be more scalable.

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.

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.

Expansion

In this example, annotations are used to declare pointcuts, and I implement to declare the whitelist to be verified through the annotation parameters. If you need to add other whitelists later, such as verifying through UID, you can add methods such as uid () to the annotation to achieve custom verification. In addition, spring's AOP also supports pointcut declaration methods such as execution (execution method), bean (execution method of a Bean object matching a specific name), and notification methods such as @ Around (executed during target function execution) and @ After (after method execution). In this way, the function has been implemented, but the leader is not satisfied with = _ =, because too much AOP is used in the project, so I am advised to do it in a different way. Well, we have to do it.

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 {@ Override public 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 } @ Override public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {/ / method executes} @ Override public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {/ / execute}} extension after view view rendering finishes

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 {@ Override public void addInterceptors (InterceptorRegistry registry) {registry.addInterceptor (new WhitelistInterceptor ()) .addPathPatterns ("/ *") .order (1); / / the order of interceptor enabled path can be configured here. When multiple interceptors exist, any interceptor returns 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.

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 implemented AuthParamResolver classes are as follows:

@ Componentpublic class AuthParamResolver implements HandlerMethodArgumentResolver {@ Override public boolean supportsParameter (MethodParameter parameter) {return parameter.getParameterType (). Equals (AuthParam.class);} @ Override public 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;}} extension

Of course, using the parameter parser also needs to be configured separately, and we also configure it within WebMvcConfigurerAdapter:

Configurationpublic class MvcConfiguration extends WebMvcConfigurerAdapter {@ Override public 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.

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 {@ Override public void init (FilterConfig filterConfig) throws ServletException {/ / is called once after initialization} @ Override public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, and ServletException {/ / determines whether to intercept chain.doFilter (request, response) / / request to invoke the}} extension once when the call} @ Override public void destroy () {/ / is destroyed

Filter also requires a display configuration:

@ Configurationpublic class FilterConfiguration {@ Bean public FilterRegistrationBean someFilterRegistration () {FilterRegistrationBean registration = new FilterRegistrationBean (); registration.setFilter (new WhitelistFilter ()); registration.addUrlPatterns ("/ *"); registration.setName ("whitelistFilter"); registration.setOrder (1); / / sets the order return registration in which the filter is called }} this is the end of the content of "what are the ways of SpringBoot project authentication". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report