title: How to add a custom security annotation to Spring MVC controller method
body: <p>I am using Java 8, Spring MVC 4, Spring Boot, and Gradle for my REST application.</p>
  
  <p>I would like to add security to my REST application via custom method annotations within certain Spring MVC 4 controllers.</p>
  
  <p>Here is a basic example.</p>
  
  <p><strong>HomeController.java</strong></p>
  
  <pre><code>package myapp;
  
  import org.springframework.web.bind.annotation.RestController;
  import org.springframework.web.bind.annotation.RequestMapping;
  
  @RestController
  @RequestMapping("/")
  public class HomeController {
  
      @RequestMapping("/")
      public String index() {
          return "&lt;h1&gt;Hello, World!&lt;/h1&gt;&lt;p&gt;Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum&lt;/p&gt;";
      }
  
      @CustomSecurityAnnotation
      @RequestMapping("/secure")
      public String secure() {
          return "&lt;h1&gt;Secured!&lt;/h1&gt;&lt;p&gt;Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum&lt;/p&gt;";
      }
  }
  </code></pre>
  
  <p>I would like <code>CustomSecurityAnnotation</code> to run a custom method that will check the headers of the incoming REST request, look at HTTP header <code>Authorization</code>, pull the value provided (if one was provided), and run code against that value to validate the request <strong>before</strong> allowing the method to proceed. The annotation should have the ability to override the response and provide a HTTP 401 or 403 if the authorization is invalid, and allow the method under the annotation to run if I decide the annotation custom method passed successfully. </p>
  
  <p>I realize there is something similar I could do with <code>PreAuthorize</code> and other MVC annotations but I'm looking at packaging up custom logic within a method inside a single annotation to be used on any method on any controller of my choosing.</p>
  
  <p>Thanks!</p>