title: Getting Authentication To Work With Spring Boot On Tomcat
body: <p>I am trying to get <code>spring-boot-starter-security</code> to work along with <code>spring-boot-starter-web</code> and <code>spring-boot-starter-tomcat</code>. I tried following the guide from <a href="https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-secure" rel="nofollow">spring-boot-sample-secure</a> and <a href="https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples/spring-boot-sample-web-secure" rel="nofollow">spring-boot-sample-web-secure</a> however I did not get it to work.</p>
  
  <p>I am trying to build a REST application without any ui interactions. Hence I found both samples are not fully suitable for my purpose. Currently my solution is by using AOP.</p>
  
  <p><a href="https://github.com/rashidi/spring-boot-openshift/blob/master/src/main/java/my/zin/rashidi/openshift/tomcat/monitor/ControllerMonitor.java" rel="nofollow">ControllerMonitor.java</a>:</p>
  
  <pre><code>@Before("execution(* my.zin.rashidi.openshift.tomcat.controller.*.*(..)) &amp;&amp; args(authorization, ..)")
  public void authenticate(String authorization) {
  
      if (!isEmpty(authorization)) {
          SecurityContextHolder.getContext().setAuthentication(
                  new UsernamePasswordAuthenticationToken("user", "N/A",
                          AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"))
          );
      }
  }
  </code></pre>
  
  <p><a href="https://github.com/rashidi/spring-boot-openshift/blob/master/src/main/java/my/zin/rashidi/openshift/tomcat/controller/UserController.java" rel="nofollow">UserController.java</a>:</p>
  
  <pre><code>@RequestMapping(method = GET)
  public ResponseEntity&lt;User&gt; get(@RequestHeader String authorization, @RequestBody User user) {
      HttpStatus status = OK;
      User returnObject = null;
  
      try {
          returnObject = service.get(user);
      } catch (AuthenticationCredentialsNotFoundException e) {
          status = UNAUTHORIZED;
      }
  
      return new ResponseEntity&lt;User&gt;(returnObject, status);
  }
  </code></pre>
  
  <p>The solutions is working for me. However I would like to know if this is a good solution. I'm curious if there is a better solution.</p>
  
  <p>Thanks in advanced for your helps!</p>