title: How to secure REST API with Spring Boot and Spring Security?
body: <p>I know that securing REST API is widely commented topic but I'm not able to create a small prototype that meets my criteria (and I need to confirm that these criteria are realistic). There are so many options how to secure resources and how work with Spring security, I need to clarify if my needs are realistic.</p>
  
  <p><strong>My requirements</strong></p>
  
  <ul>
  <li>Token based authenticator - users will provide its credentials and get unique and time limited access token. I would like to manage token creation, checking validity, expiration in my own implementation.</li>
  <li>Some REST resources will be public - no need to authenticate at all,</li>
  <li>Some resources will be accessible only for users with administrator rights,</li>
  <li>Other resource will be accessible after authorization for all users.</li>
  <li>I don't want to use Basic authentication</li>
  <li>Java code configuration (not XML)</li>
  </ul>
  
  <p><strong>Current status</strong></p>
  
  <p>My REST API works very well, but now I need to secure it. When I was looking for a solution I created a <code>javax.servlet.Filter</code> filter:</p>
  
  <pre><code>  @Override
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
  
          HttpServletRequest request = (HttpServletRequest) req;
  
          String accessToken = request.getHeader(AUTHORIZATION_TOKEN);
          Account account = accountDao.find(accessToken);
  
          if (account == null) {    
              throw new UnauthorizedException();    
          }
  
          chain.doFilter(req, res);
  
      }
  </code></pre>
  
  <p>But this solution with <code>javax.servlet.filters</code> doesn't work as I need because there is an issue with exception handling via <code>@ControllerAdvice</code> with Spring <code>servlet dispatcher</code>.</p>
  
  <p><strong>What I need</strong></p>
  
  <p>I would like to know if these criteria are realistic and get any help, how to start  securing REST API with Spring Security. I read many tutorials (e.g. <a href="https://github.com/spring-projects/spring-data-examples/tree/master/rest/security" rel="noreferrer">Spring Data REST + Spring Security</a>) but all work in very basic configuration - users with <strong>their credentials are stored in memory</strong> in configuration and I need to work with DBMS and create own authenticator.</p>
  
  <p><strong>Please give me some ideas how to start.</strong></p>