我试图通过https://github.com/callicoder/spring-security-react-ant-design-polls-app了解Full-stack Web应用程序的代码 但是我不明白spring-boot如何知道当前的用户正在登录。
这是调用api的ReactJS(前端)代码。
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(后端)代码
@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);
}
答案 0 :(得分:1)
@CurrentUser UserPrincipal currentUser
,将 UserPrincipal currentUser 参数添加到 Controller 方法中后,它将自动从上下文填充对象,您可以您可以通过调用 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);
...