Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev. The current series is about building a Kanban API with Spring.

Let's Build an API Together - Part 27

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.setId(null);

    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.


comments powered by Disqus