title: Spring Boot @PreAuthorize hasAuthority not working
body: <p>I have implemented SpringSecurity with JWT, all working nicely except one thing</p>
  <p><code>@PreAuthorize(&quot;hasAuthority('admin:read')&quot;)</code> isnt working, it gives</p>
  <blockquote>
  <p>403 FORBIDDEN error</p>
  </blockquote>
  <p>I will share parts of important codes. The token return all authorities properly which I added as SimpleGrantedAuthority</p>
  <p>SecurityConfig</p>
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  ...logic
  }
  </code></pre>
  <p>AccountController</p>
  <pre><code>@RestController
  @RequestMapping(&quot;/api&quot;)
  public class AccountController {
  
      //this works
      @RequestMapping(value = &quot;/accounts&quot;, method = RequestMethod.GET)
      @PreAuthorize(&quot;hasAnyRole('ROLE_ADMIN')&quot;)
      public ResponseEntity&lt;?&gt; loadAll() {
          List&lt;AccountDTO&gt; res = accountService.loadAll();
          return new ResponseEntity(new ResponseWrapper(res), HttpStatus.OK);
      }
  
      //this doesn't work
      @RequestMapping(value = &quot;/accounts/{uid}&quot;, method = RequestMethod.GET)
      @PreAuthorize(&quot;hasAuthority('admin:read')&quot;)
      ResponseEntity&lt;?&gt; findByUId(@PathVariable String uid) throws Exception {
          AccountDTO dto = this.accountService.findByUid(uid);
          return new ResponseEntity&lt;&gt;(new ResponseWrapper(dto), HttpStatus.OK);
      }
  }
  </code></pre>
  <p>Token</p>
  <pre><code>{
    &quot;sub&quot;: &quot;nenad.arbutina&quot;,
    &quot;authorities&quot;: [
      {
        &quot;authority&quot;: &quot;ROLE_ADMIN&quot;
      },
      {
        &quot;authority&quot;: &quot;admin:read&quot;
      },
      {
        &quot;authority&quot;: &quot;admin:create&quot;
      },
      {
        &quot;authority&quot;: &quot;admin:update&quot;
      },
      {
        &quot;authority&quot;: &quot;admin:delete&quot;
      }
    ],
    &quot;iat&quot;: 1631111042,
    &quot;exp&quot;: 1632261600
  }
  </code></pre>
  <p>update on code. When debugged I am getting only ROLE_ADMIN, so I am confused</p>
  <p>SecurityConfig</p>
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
      private final MyUserDetailService myUserDetailService;
      private final SecretKey secretKey;
      private final JwtConfig jwtConfig;
  
      @Autowired
      public SecurityConfig(
                            MyUserDetailService myUserDetailService,
                            SecretKey secretKey,
                            JwtConfig jwtConfig) {
  
          this.myUserDetailService = myUserDetailService;
          this.secretKey = secretKey;
          this.jwtConfig = jwtConfig;
      }
      @Bean
      PasswordEncoder getEncoder() {
          return new BCryptPasswordEncoder();
      }
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
                  .csrf().disable()
                  .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                  .and()
                  .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
                  .addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig), JwtUsernameAndPasswordAuthenticationFilter.class)
                  .authorizeRequests()
                  .antMatchers(&quot;/&quot;, &quot;index&quot;,&quot;/css/*&quot;, &quot;/js/*&quot;).permitAll()
                  .anyRequest()
                  .authenticated();
      }
  
      @Override
      protected void configure(AuthenticationManagerBuilder auth) throws Exception {
          auth.authenticationProvider(daoAuthenticationProvider());
      }
  
      @Bean
      public DaoAuthenticationProvider daoAuthenticationProvider() {
          DaoAuthenticationProvider provider = new 
          DaoAuthenticationProvider();
          provider.setPasswordEncoder(getEncoder());
          provider.setUserDetailsService(myUserDetailService);
          return provider;
      }
  }
  </code></pre>
  <p>JwtTokenVerifier</p>
  <pre><code>public class JwtTokenVerifier extends OncePerRequestFilter {
  
      private final SecretKey secretKey;
      private final JwtConfig jwtConfig;
  
      public JwtTokenVerifier(SecretKey secretKey,
                              JwtConfig jwtConfig) {
          this.secretKey = secretKey;
          this.jwtConfig = jwtConfig;
      }
  
      @Override
      protected void doFilterInternal(HttpServletRequest request,
                                      HttpServletResponse response,
                                      FilterChain filterChain) throws ServletException, IOException {
  
          String authorizationHeader = request.getHeader(jwtConfig.getAuthorizationHeader());
  
          if (Strings.isNullOrEmpty(authorizationHeader) || !authorizationHeader.startsWith(jwtConfig.getTokenPrefix())) {
              filterChain.doFilter(request, response);
              return;
          }
          String token = authorizationHeader.replace(jwtConfig.getTokenPrefix(), &quot;&quot;);
          try {
  
  
              Jws&lt;Claims&gt; claimsJws = Jwts.parser()
                      .setSigningKey(secretKey)
                      .parseClaimsJws(token);
              Claims body = claimsJws.getBody();
              String username = body.getSubject();
  
              List&lt;Map&lt;String, String&gt;&gt; authorities = (List&lt;Map&lt;String, String&gt;&gt;) body.get(&quot;authorities&quot;);
  
              Set&lt;SimpleGrantedAuthority&gt; simpleGrantedAuthorities = authorities.stream()
                      .map(m -&gt; new SimpleGrantedAuthority(m.get(&quot;authority&quot;)))
                      .collect(Collectors.toSet());
  
              Authentication authentication = new UsernamePasswordAuthenticationToken(
                      username,
                      null,
                      simpleGrantedAuthorities
              );
  
              SecurityContextHolder.getContext().setAuthentication(authentication);
  
              filterChain.doFilter(request, response);
  
          } catch (JwtException e ){
              throw new IllegalStateException(String.format(&quot;Token %s is not to be trusted&quot;, token));
          }
      }
  }
  </code></pre>