Я пытаюсь понять коды веб-приложения Full-stack на https://github.com/callicoder/spring-security-react-ant-design-polls-app но я не понимаю, как spring-boot знает, какой текущий пользователь входит в систему.
это код ReactJS (внешний интерфейс), который вызывает API.
export function getUserCreatedPolls(username, page, size) {
page = page || 0;
size = size || POLL_LIST_SIZE;
return request({
url: API_BASE_URL + "/users/" + username + "/polls?page = " + page + "&size = " + size,
method: 'GET'
});
}
И это код spring-boot (back-end), который получает переменные от внешнего интерфейса.
@GetMapping("/users/{username}/polls")
public PagedResponse<PollResponse> getPollsCreatedBy(@PathVariable(value = "username") String username,
@CurrentUser UserPrincipal currentUser,
@RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page,
@RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size) {
return pollService.getPollsCreatedBy(username, currentUser, page, size);
}
@CurrentUser UserPrincipal currentUser , когда вы добавили параметр UserPrincipal текущий пользователь в методы Spring Контроллер, он автоматически заполнит объект из контекста, вы можете сделать это самостоятельно, вызвав класс SecurityContextHolder и получить текущий аутентифицированный пользователь
...
// Get The Jwt token from the HTTP Request
String jwt = getJwtFromRequest(request);
// Check The validation of JWT - if true the user is trusted
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
/*
Note that you could also encode the user's username and roles inside JWT claims
and create the UserDetails object by parsing those claims from the JWT.
That would avoid the following database hit. It's completely up to you.
*/
// Get the user object
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// Fill the security context with this user
SecurityContextHolder.getContext().setAuthentication(authentication);
...