Let's Build an API Together - Part 25

Last Update: 31.01.2018. By Jens in API Series | APIs | Newsletter

The API will expose endpoints for login and register new users.

  • /register - POST with the user model in the body
  • /login - POST request with basic auth. The endpoint does not do anything but is used as an entry for Spring Security. If the request is successful with basic auth, Spring will assign a session (Spring session - configuration comes next time)

I implemented both in the same controller as they are related. We also use the password encoder here and encode the password of a user during registration.

public class UserController {

    private UserRepository userRepository;

    private PasswordEncoder passwordEncoder;

    public void login() {
        // spring session automatically returns the session token in the header

    public ResponseEntity<String> registerUser(@RequestBody User userIn) {
        if (StringUtils.isEmpty(userIn.getUsername()) || StringUtils.isEmpty(userIn.getPassword())) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        User userDb = new User();

        userDb = userRepository.save(userDb);
        return new ResponseEntity<String>(userDb.getId().toString(), HttpStatus.CREATED);

Yes, we could move the business logic in the registration method to AppUserDetailsService or even its own class. However, its just used once, so there’s not a real benefit for that.

Next time we’ll introduce Spring Session for authN/Z handling. No worries, we do not authenticate with an HTTPSession.

Want content like this in your inbox each workday irregularly? No BS, spam or tricks... just useful content:

I understand and agree to the privacy policy