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.

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public void login() {
        // spring session automatically returns the session token in the header
    }

    @PostMapping("/register")
    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.setUsername(userIn.getUsername());
        userDb.setPassword(passwordEncoder.encode(userIn.getPassword()));

        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.