Access is denied when using Security

Cause: If the interface that allows anonymous access carries a token, there is no access permission.

Solution 1: Change to permitAll

anonymous() allows anonymous users to access and does not allow logged-in users to access
permitAll() can be accessed regardless of whether you are logged in or not.

Option 2: If there are too many interfaces that need to be released, it will be too cumbersome to fill them in one by one. Use annotations to intercept to determine whether to release or not.

1. Add custom annotations to mark anonymous access methods.

@Inherited
@Documented
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnonymousAccess {


}

2. Add each method annotation

@AnonymousAccess
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.POST)
public @interface AnonymousPostMapping {

    /**
     * Alias for {@link RequestMapping#name}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String name() default "";

    /**
     * Alias for {@link RequestMapping#value}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String[] value() default {};

    /**
     * Alias for {@link RequestMapping#path}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String[] path() default {};

    /**
     * Alias for {@link RequestMapping#params}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String[] params() default {};

    /**
     * Alias for {@link RequestMapping#headers}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String[] headers() default {};

    /**
     * Alias for {@link RequestMapping#consumes}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String[] consumes() default {};

    /**
     * Alias for {@link RequestMapping#produces}.
     */
    @AliasFor(annotation = RequestMapping.class)
    String[] produces() default {};

}
@AnonymousAccess
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RequestMapping(method = RequestMethod.GET)
public @interface AnonymousGetMapping {

      /**
       * Alias for {@link RequestMapping#name}.
       */
      @AliasFor(annotation = RequestMapping.class)
      String name() default "";

      /**
       * Alias for {@link RequestMapping#value}.
       */
      @AliasFor(annotation = RequestMapping.class)
      String[] value() default {};

      /**
       * Alias for {@link RequestMapping#path}.
       */
      @AliasFor(annotation = RequestMapping.class)
      String[] path() default {};

      /**
       * Alias for {@link RequestMapping#params}.
       */
      @AliasFor(annotation = RequestMapping.class)
      String[] params() default {};

      /**
       * Alias for {@link RequestMapping#headers}.
       */
      @AliasFor(annotation = RequestMapping.class)
      String[] headers() default {};

      /**
       * Alias for {@link RequestMapping#consumes}.
       *
       * @since 4.3.5
       */
      @AliasFor(annotation = RequestMapping.class)
      String[] consumes() default {};

      /**
       * Alias for {@link RequestMapping#produces}.
       */
      @AliasFor(annotation = RequestMapping.class)
      String[] produces() default {};

}

3. Add release rules in config

//Injection
@Autowired
 private ApplicationContext applicationContext;


 @Override
      protected void configure(HttpSecurity http) throws Exception {
            //Search for anonymous tag url: @AnonymousAccess
            RequestMappingHandlerMapping requestMappingHandlerMapping = (RequestMappingHandlerMapping) applicationContext.getBean("requestMappingHandlerMapping");
            Map<RequestMappingInfo, HandlerMethod> handlerMethodMap = requestMappingHandlerMapping.getHandlerMethods();
            // Get anonymous tag
            Map<String, Set<String>> anonymousUrls = getAnonymousUrl(handlerMethodMap);
            http
                    //Close csrf
                    .csrf().disable()
                    //Get SecurityContext without using Session
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests()
                    .antMatchers(
                            HttpMethod.GET,
                            "/*.html",
                            "/**/*.html",
                            "/**/*.css",
                            "/**/*.js",
                            "/webSocket/**"
                    ).permitAll()
                    .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui",
                            "/swagger-resources", "/swagger-resources/configuration/security",
                            "/swagger-ui.html", "/webjars/**").permitAll()
                
                    // swagger documentation
                    .antMatchers("/auth/swagger-ui.html").permitAll()
                    .antMatchers("/swagger-resources/**").permitAll()
                    // Customize anonymous access to all URLs: allow anonymous and token access, and refine it to each Request type
                    //GET
                    .antMatchers(HttpMethod.GET, anonymousUrls.get(RequestMethodEnum.GET.getType()).toArray(new String[0])).permitAll()
                    // POST
                    .antMatchers(HttpMethod.POST, anonymousUrls.get(RequestMethodEnum.POST.getType()).toArray(new String[0])).permitAll()
                    //PUT
                    .antMatchers(HttpMethod.PUT, anonymousUrls.get(RequestMethodEnum.PUT.getType()).toArray(new String[0])).permitAll()
                    // PATCH
                    .antMatchers(HttpMethod.PATCH, anonymousUrls.get(RequestMethodEnum.PATCH.getType()).toArray(new String[0])).permitAll()
                    //DELETE
                    .antMatchers(HttpMethod.DELETE, anonymousUrls.get(RequestMethodEnum.DELETE.getType()).toArray(new String[0])).permitAll()
                    // All types of interfaces are allowed
                    .antMatchers(anonymousUrls.get(RequestMethodEnum.ALL.getType()).toArray(new String[0])).permitAll()
                    // All requests except the above require authentication.
                    .anyRequest().authenticated();

            //Add the token verification filter to the filter chain
            http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

            //Authentication failure exception handler
            http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).
                    accessDeniedHandler(accessDeniedHandler);

            http.cors();
      }

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138,184 people are learning the system