java - Spring security AntMatcher 不工作

标签 java spring spring-boot spring-security jwt

这是我配置 spring security 的方式,在 Controller 中我获得 ROLE_ANONYMOUS 作为权限。看起来安全性并没有拦截请求并检查 JWT。 如何配置antmatcher..?

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter
{

   @Override
   public void configure(HttpSecurity http) throws Exception
   {
      http.authorizeRequests()
            .antMatchers("/actuator/**", "/api-docs/**").permitAll()
            .antMatchers("/notes/**").hasAnyAuthority("USER").anyRequest().authenticated();
   }

}

下面是我的 Controller 代码

@RestController
@RequestMapping("/notes")
public class NoteController
{
   @Autowired
   private IUserService userService;

   @Autowired
   private INoteService noteService;

   static MessageSourceAccessor messageAccesser =  ApplicationConfiguration.getMessageAccessor();

   private final Logger logger = LoggerFactory.getLogger(NoteController.class);

   @RequestMapping(value = "/addnote", method = RequestMethod.POST)
   public ResponseEntity<Response> addNote(@RequestBody NoteDto note, HttpSession session)
   {
      Authentication ath = SecurityContextHolder.getContext().getAuthentication();
      int userId = 5;
      logger.debug("Adding note :-", note);
      Response response = new Response();
      try {
         User user = userService.getUserById(userId);
         if (user == null) {
            response.setStatus(111);
            response.setResponseMessage(ApplicationConfiguration.getMessageAccessor().getMessage("111"));
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
         }
         noteService.saveNote(note, user);

      } catch (Exception e) {
         logger.error(e.getMessage());
         FNException fn = new FNException(101, new Object[] { "Adding Note - " + e.getMessage() }, e);
         return new ResponseEntity<>(fn.getErrorResponse(), HttpStatus.INTERNAL_SERVER_ERROR);
      }
      response.setStatus(200);
      response.setResponseMessage(messageAccesser.getMessage("200"));
      return new ResponseEntity<>(response, HttpStatus.OK);
   }

更新 看起来 Ant 匹配器不起作用。这是我访问 api 时的日志。

DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.s.w.u.matcher.OrRequestMatcher.matches line: 72 - No matches found
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 5 of 10 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 6 of 10 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 7 of 10 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 8 of 10 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.s.w.a.AnonymousAuthenticationFilter.doFilter line: 100 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 9 of 10 in additional filter chain; firing Filter: 'SessionManagementFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.s.w.s.SessionManagementFilter.doFilter line: 124 - Requested session ID DE97FB345788E4AB200B922552573A31 is invalid.
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 325 - /notes/addnote at position 10 of 10 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.security.web.FilterChainProxy.doFilter line: 310 - /notes/addnote reached end of additional filter chain; proceeding with original chain
DEBUG [http-nio-8080-exec-3]: 2018-04-18 16:31:03 o.s.web.servlet.DispatcherServlet.doService line: 869 - DispatcherServlet with name 'dispatcherServlet' processing POST request for [/notes/addnote]

最佳答案

尝试WebSecurityConfigurerAdapter,您可以引用下面我的演示。我定制了一些过滤器来进行验证,如果不需要就删除它。

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.addFilterBefore(new CaptchaAuthenticationFilter("/login", "/login?error2"), UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()
                .antMatchers("/").hasRole("USER")
                .antMatchers("/index").hasRole("USER")
                .antMatchers("/message/*").hasRole("USER")
                .anyRequest().permitAll()
                .and().formLogin().loginPage("/login").defaultSuccessUrl("/index").failureUrl("/login?error1").permitAll()
                .and().rememberMe().tokenValiditySeconds(60*60*7).key("message")
                .and().logout().logoutUrl("/logout").logoutSuccessUrl("/login").permitAll();
    }

    @Bean
    public AuthenticationProvider authenticationProvider(){
        DaoAuthenticationProvider authenticationProvider=new CustomAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService());
        return authenticationProvider;
    }

    @Bean
    public UserDetailsService userDetailsService(){
        return new CustomUserDetailService();
    }

}

关于java - Spring security AntMatcher 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49897276/

相关文章:

java - 在某些情况下捕获匿名类中开关周围的计数器?

java - 如何将 ArrayUtils 用于对象数组,它不会删除数组的内容

java - Spring JdbcTemplate 在创建存储过程时抛出错误

java - 超过锁定等待超时;尝试用 spring 和 Mysql 重启事务 Java

java - 如何为具有 Excel 工作表文件的 InputStream 构造响应正文?

java - Spring 数据 : Create entities (and DB entries) using boolean fields of another entity

java - Intellij,如何在我自己的项目中使用.class(无源代码)

java - 启动多模块maven/spring项目

java - 在 springboot 中创建名为 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaConfiguration 的 bean 时出错

java - Maven/Spring 项目中缺少工件的问题