title: Spring security: public API to register new user
body: <p>I have a use-case where I want to <code>HTTP POST</code> a <code>userName</code> as JSON to my service, and the service should then register a new user (with a given <code>userName</code> and an auto-generated password).</p>
  
  <p><strong>JSON</strong></p>
  
  <pre><code>{
  "userName": "Sia"
  }
  </code></pre>
  
  <p>I am using <code>Spring Security</code>, and the problem I am facing is that:</p>
  
  <p>Whenever I try to <code>HTTP POST</code> a <code>userName</code>, the service already asks for authentication (username and password). This is not why I want. I want a registration API to be completely public. Meaning that everyone (unauthorized) can <code>HTTP POST</code> a new username and thus "open the account".</p>
  
  <p>I am not sure how I could achieve the wanted behaviour. Parts of the service should be public (like creating a new user as described above), and some parts should indeed require authentication (of the users that are created in the described public <code>POST</code> procedure). Any advice?</p>
  
  <p><strong>pom.xml</strong></p>
  
  <pre><code>  &lt;dependencies&gt;
      &lt;dependency&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
      &lt;/dependency&gt;
  
      &lt;dependency&gt;
          &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
          &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;
      &lt;/dependency&gt;
    &lt;/dependencies&gt;
  </code></pre>
  
  <p><strong>UserController.java</strong></p>
  
  <pre><code>@Autowired
  private UserService service;    
  
  @RequestMapping(method = RequestMethod.POST, value = "/user")
  public void register(@PathVariable String userName) {
      System.err.println("!!!!!!!!!!!"); // this line never gets executed
  
      service.save(userName);
  }
  </code></pre>
  
  <p><strong>UserService.java</strong></p>
  
  <pre><code>public void save(String userName) {     
      String password = pwGenerator.generate();       
      repository.save(new User(userName, password));
  }
  </code></pre>