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

How to realize General Auth Authentication by Springboot

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 "Springboot how to achieve general Auth authentication" related knowledge, editor through the actual case to show you the operation process, the method of operation is simple and fast, practical, I hope that this "Springboot how to achieve general Auth authentication" article can help you solve the problem.

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:

@ Aspect public 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 matching a Bean object with 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. Another concern: code ape technology column, reply in the background: "interview Treasure Book" can be obtained, high-definition PDF latest version of 3625 pages of Internet interview questions.

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, ServletException {/ / determines whether to intercept chain.doFilter (request, response); / / request calls}} 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 introduction of "how to achieve General Auth Certification in Springboot". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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