2

This is the way I have configured spring security, in controller I'm getting ROLE_ANONYMOUS as authority. Looks like security is not intercepting the request and checking for JWT. How to configure 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();
   }

}

Below is my controller code

@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);
   }

UPDATE Looks like antmatchers are not working. Here is the log when I hit the 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]
Siddharth Gharge
  • 112
  • 3
  • 13
  • Do you have any other Spring Security configuration with a lower order? The best way to solve your problem is, that you add Spring Security logs with `DEBUG` level to your question. It will show the reason. – dur Apr 18 '18 at 10:47
  • Looks like antmatcher is not working. I have added the log in question. Please do check. – Siddharth Gharge Apr 18 '18 at 11:05
  • Unfortunatly you have to provide more logs. It isn't clear which filter chain is executed. Spring Boot has a lot of filter chains (static resources, authorization server, resource server, Spring Boot default, Actuator, ...) – dur Apr 18 '18 at 11:21
  • Is there a reason you specifically need to be using `ResourceServerConfigurerAdapter` over `WebSecurityConfigurerAdapter`? – TwiN Apr 18 '18 at 11:28

2 Answers2

1

Try WebSecurityConfigurerAdapter, you can refer to my demo below. I have customed some filters for validation, If you don't need just remove it.

@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();
    }

}
Dave Pateral
  • 1,415
  • 1
  • 14
  • 21
0

What version of spring-boot and spring-security are you using?

The @EnableResourceServer annotation adds a filter of type OAuth2AuthenticationProcessingFilter automatically to the Spring Security filter chain.

So to your "extends ResourceServerConfigurerAdapter" be applyed before the OAuth2AuthenticationProcessingFilter, you'll need to annotate it with @Order (-1)

@Configuration
@EnableResourceServer
@Order(-1)
public class ResourceServerConfig extends ResourceServerConfigurerAdapter{
[...]
Petter
  • 318
  • 2
  • 13