Let's Build an API Together - Part 27

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

Now that we can register a new user and login, it is time for assigning boards to the logged in user.

We do so in the TaskService like:

public List<Board> getBaords() {
    return boardRepository.findAllByUser(((UserPrincipal )SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());

public Board createBoard(Board board) {

    board.setUser(((UserPrincipal )SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId());
    return boardRepository.save(board);

Via the SecurityContextHolder, we can get at any place in our code, as long as it is running in the same thread. THe Principal is a representation of the logged in user, and we provided our own before by returning UserPrincipal in the UserDetails_Service.

So, the first filters the board lists by the user and the second will add the userid when we create a new board.

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