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 the opening of Interface by Spring Security

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

Share

Shulou(Shulou.com)05/31 Report--

In this article, the editor introduces in detail "how to achieve interface opening in Spring Security". The content is detailed, the steps are clear, and the details are handled properly. I hope this article "how to achieve interface opening in Spring Security" can help you solve your doubts. Let's follow the editor's ideas to learn new knowledge.

1.SpringBoot version

The version of Spring Boot on which this article is based is 2.6.7

two。 Realization idea

Create a new AnonymousAccess annotation that is applied to the Controller method

Create an enumeration class that holds all the request modes

By judging whether the annotation exists on the Controller method

Policy configuration on SecurityConfig

3. Implementation process 3.1 New annotation @ Inherited@Documented@Target ({ElementType.METHOD,ElementType.ANNOTATION_TYPE}) @ Retention (RetentionPolicy.RUNTIME) public @ interface AnonymousAccess {} 3.2 New request enumeration class

This class holds all request types, and the code is as follows:

@ Getter@AllArgsConstructorpublic enum RequestMethodEnum {/ * search @ AnonymousGetMapping * / GET ("GET"), / * search @ AnonymousPostMapping * / POST ("POST"), / * * search @ AnonymousPutMapping * / PUT ("PUT"), / * * search @ AnonymousPatchMapping * / PATCH ("PATCH") / * search @ AnonymousDeleteMapping * / DELETE ("DELETE"), / * otherwise all Request interfaces will be released * / ALL ("All") / * Request type * / private final String type; public static RequestMethodEnum find (String type) {for (RequestMethodEnum value: RequestMethodEnum.values ()) {if (value.getType (). Equals (type)) {return value;}} return ALL;}} 3.3 determine whether the note exists on the Controller method

Define a private method getAnonymousUrl in the SecurityConfig class. The main purpose of this method is to determine which methods of controller are annotated with AnonymousAccess.

Private Map getAnonymousUrl (Map handlerMethodMap) {Map anonymousUrls = new HashMap (8); Set get = new HashSet (); Set post = new HashSet (); Set put = new HashSet (); Set patch = new HashSet (); Set delete = new HashSet (); Set all = new HashSet (); for (Map.Entry infoEntry: handlerMethodMap.entrySet ()) {HandlerMethod handlerMethod = infoEntry.getValue () AnonymousAccess anonymousAccess = handlerMethod.getMethodAnnotation (AnonymousAccess.class); if (null! = anonymousAccess) {List requestMethods = new ArrayList (infoEntry.getKey (). GetMethodsCondition (). GetMethods ()); RequestMethodEnum request = RequestMethodEnum.find (requestMethods.size () = 0? RequestMethodEnum.ALL.getType (): requestMethods.get (0). Name (); switch (Objects.requireNonNull (request)) {case GET: get.addAll (infoEntry.getKey (). GetPatternsCondition (). GetPatterns ()); break Case POST: post.addAll (infoEntry.getKey (). GetPatternsCondition (). GetPatterns ()); break; case PUT: put.addAll (infoEntry.getKey (). GetPatternsCondition (). GetPatterns ()); break Case PATCH: patch.addAll (infoEntry.getKey (). GetPatternsCondition (). GetPatterns ()); break; case DELETE: delete.addAll (infoEntry.getKey (). GetPatternsCondition (). GetPatterns ()); break Default: all.addAll (infoEntry.getKey (). GetPatternsCondition (). GetPatterns ()); break;} anonymousUrls.put (RequestMethodEnum.GET.getType (), get); anonymousUrls.put (RequestMethodEnum.POST.getType (), post) AnonymousUrls.put (RequestMethodEnum.PUT.getType (), put); anonymousUrls.put (RequestMethodEnum.PATCH.getType (), patch); anonymousUrls.put (RequestMethodEnum.DELETE.getType (), delete); anonymousUrls.put (RequestMethodEnum.ALL.getType (), all); return anonymousUrls;} 3.4 configure policies on SecurityConfig

Get the Bean of requestMappingHandlerMapping through a SpringUtil utility class, and then find out the tagged AnonymousAccess interface through the getAnonymousUrl method. Finally, it is refined to each Request type through antMatchers.

@ Override protected void configure (HttpSecurity httpSecurity) throws Exception {/ / search for anonymous tags url: @ AnonymousAccess RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) SpringUtil.getBean ("requestMappingHandlerMapping"); Map handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods (); / / get anonymous tags Map anonymousUrls = getAnonymousUrl (handlerMethodMap) HttpSecurity / / disable CSRF .csrf () .disable () .authorizeRequests () / customize anonymous access to all url releases: fine-tune to each Request type / / GET .antMatrices (HttpMethod.GET AnonymousUrls.get (RequestMethodEnum.GET.getType ()) .toArray (new String [0]). PermitAll () / / POST .antMatrices (HttpMethod.POST,anonymousUrls.get (RequestMethodEnum.POST.getType ()) .toArray (new String [0])) .permitAll () / / PUT .antMatrices (HttpMethod.PUT) AnonymousUrls.get (RequestMethodEnum.PUT.getType ()) .toArray (new String [0]). PermitAll () / / PATCH .antMatrices (HttpMethod.PATCH,anonymousUrls.get (RequestMethodEnum.PATCH.getType ()) .toArray (new String [0])) .permitAll () / / DELETE .antMatrices (HttpMethod.DELETE) AnonymousUrls.get (RequestMethodEnum.DELETE.getType ()) .toArray (new String [0]). PermitAll () / all types of interfaces are released .antMatrices (anonymousUrls.get (RequestMethodEnum.ALL.getType ()) .toArray (new String [0]). PermitAll () / all requests require authentication .anyRequest () .Array () Application of 3. 5 in Controller method

It is very convenient to annotate the open interface on Controller so that you can access it without authentication. For example, if the CAPTCHA does not require authentication access, the code is as follows:

@ ApiOperation (value = "get CAPTCHA", notes = "get CAPTCHA") @ AnonymousAccess @ GetMapping ("/ code") public Object getCode () {Captcha captcha = loginProperties.getCaptcha (); String uuid = "code-key-" + IdUtil.simpleUUID (); / / when the CAPTCHA type is arithmetic and the length > = 2, the probability of captcha.text () is floating-point String captchaValue = captcha.text () If (captcha.getCharType ()-1 = = LoginCodeEnum.ARITHMETIC.ordinal () & & captchaValue.contains (".") {captchaValue = captchaValue.split ("\\.") [0];} / / Save redisUtils.set (uuid,captchaValue,loginProperties.getLoginCode (). GetExpiration (), TimeUnit.MINUTES) / / CAPTCHA information Map imgResult = new HashMap (2) {{put ("img", captcha.toBase64 ()); put ("uuid", uuid);}}; return imgResult;} 3.6 effect display

After reading this, the article "how to make the interface open in Spring Security" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

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