title: Unable to implement Role based access to Spring-Boot API
body: <p>I am new to Spring-Boot.I want to create an API which will have role based access with JWT token based authentication. But, unable to implement that.</p>
  
  <p>I am not using JPA &amp; Hibernate to fetch and map data. Instead I am using Ibatis.I have tried with <strong>@PreAuthorize</strong> and <strong>antMatchers &amp; hasRole</strong>, but failed. By getting user id from JWT token, I am fetching details and roles and setting those to <strong>SecurityContextHolder.getContext().setAuthentication</strong>, still not working.</p>
  
  <p>SecurityConfig</p>
  
  <pre><code>@Configuration
  @EnableWebSecurity
  @EnableGlobalMethodSecurity(prePostEnabled = true)
  public class SecurityConfig extends WebSecurityConfigurerAdapter {
  
  @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
            .csrf().disable()
  
     .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .addFilter(new JwtAuthorizationFilter(authenticationManager()))
            .authorizeRequests()
            .anyRequest().authenticated()
            .antMatchers("api/management/reports").hasRole("Supervisor");
      }
  </code></pre>
  
  <p>Controller</p>
  
  <pre><code>@RestController
  @RequestMapping("api")
  @CrossOrigin
  public class MyController {
  
      @PreAuthorize("hasRole('Supervisor')")
      @GetMapping("username")
      public String reports(){
          SecurityContext securityContext = SecurityContextHolder.getContext();
          return securityContext.getAuthentication().getName();
      }
  }
  </code></pre>
  
  <p>AuthorizationFilter</p>
  
  <pre><code>public class JwtAuthorizationFilter extends BasicAuthenticationFilter {
  
  public JwtAuthorizationFilter(AuthenticationManager authenticationManager) {
          super(authenticationManager);
      }
  
  @Override
      protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
  
  String header = request.getHeader(JwtProperties.HEADER_STRING);
  if (header == null || !header.startsWith(JwtProperties.TOKEN_PREFIX)) {
              chain.doFilter(request, response);
              return;
          }
  
          Authentication authentication = getUsernamePasswordAuthentication(request,header);
          SecurityContextHolder.getContext().setAuthentication(authentication);
  
  
          chain.doFilter(request, response);
  }
  private Authentication getUsernamePasswordAuthentication(HttpServletRequest request, String header) {
          try {
  String token = header.replace(JwtProperties.TOKEN_PREFIX,"");
  String userName = JWT.require(HMAC512(JwtProperties.SECRET.getBytes()))
                          .build()
                          .verify(token)
                          .getSubject();
  List&lt;User&gt; searchedUserList = getUserDetailsDAO().getUserDetails(userName);
  
  
      if (null !=searchedUserList &amp;&amp; searchedUserList.size()&gt;0) {
  
          User searchedUser = new User();
          searchedUser = searchedUserList.get(0);
          List&lt;RoleAccess&gt; roleAccessList = new ArrayList&lt;RoleAccess&gt;();
      XrefUsrRole oXrefUsrRole = new XrefUsrRole();
      oXrefUsrRole.setUserName(searchedUser.getUsername());
      roleAccessList = getRoleAccessDAO().getAccessDetails(oXrefUsrRole);
      List&lt;GrantedAuthority&gt; authorities = uildUserAuthority(roleAccessList);
  
      org.springframework.security.core.userdetails.User newUser = buildUserForAuthentication(searchedUser, authorities);
  
  UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(newUser, null,authorities);
                      return auth;
                  }
                  return null;
              }
              return null;
          } catch (IOException e) {
              return null;
          }
  
  private org.springframework.security.core.userdetails.User buildUserForAuthentication(User searchedUser, List&lt;GrantedAuthority&gt; authorities) {
          return new org.springframework.security.core.userdetails.User(searchedUser.getUsername(), searchedUser.getPassword(), true, true, true, true, authorities);
      }
  
      private List&lt;GrantedAuthority&gt; buildUserAuthority(List&lt;RoleAccess&gt; roleAccessList) {
          Set&lt;GrantedAuthority&gt; setAuths = new HashSet&lt;GrantedAuthority&gt;();
  
          // Build user's authorities
          for (RoleAccess userRole : roleAccessList) {
              setAuths.add(new SimpleGrantedAuthority("ROLE_"+userRole.getModifiedBy()));
          }
  
          List&lt;GrantedAuthority&gt; Result = new ArrayList&lt;GrantedAuthority&gt;(setAuths);
  
          return Result;
      }
  </code></pre>
  
  <p>In this case <strong>api/username</strong> should not accessible except users having <strong>Supervisor</strong> role.</p>