如何在 Spring 安全性中更新其他用户的状态?



假设一个User可以喜欢Posts.当一个帖子被点赞时,帖子作者(另一个User(的分数会增加。我在数据库中更新作者的状态:

post.getAuthor().incrementScore(LIKE_SCORE);
postRepository.save(post); \ author is also updated

但问题是,如果作者当前已登录,则更改不会反映给他,他应该重新登录以查看他更新的分数。

如何在 Spring 安全性中更新另一个经过身份验证的用户的状态?
请注意,我不会将用户添加到我的控制器,而是直接在模板中访问主体。我做错了吗?

用户实体:

@Entity
@EqualsAndHashCode(of = "username")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = IDENTITY)
private Long id;
@ManyToMany(mappedBy = "likers", fetch = EAGER)
private Set<Post> favorites = new HashSet<>();
@OneToMany(mappedBy = "author", fetch = EAGER)
private Set<Post> posts = new HashSet<>();
@NaturalId
private String username;
private String password;
private long score;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Set.of(new SimpleGrantedAuthority("ROLE_" + role));
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
// other overridden methods, getters and setters
}

安全配置:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll()
.and().formLogin().usernameParameter("username").passwordParameter("password")
.loginProcessingUrl("/login")
.successHandler((request, response, authentication) ->
response.getOutputStream().print(true))
.failureHandler((request, response, exception) ->
response.getOutputStream().print(""))
.and().logout()
.logoutSuccessHandler((request, response, authentication) ->
response.sendRedirect(request.getHeader("referer")))
.and().cors().disable();
}

百里香叶模板:

<div class="nav">
<div class="author">
<div class="usr-name" th:text="${#authentication.principal.username}"></div>
<div class="score" th:text="${#authentication.principal.score}"></div>
</div>
</div>

您可以使用服务器发送的事件(sse(作为http流的变体。这是为了通过 http 将事件推送到侦听器。Springboot 有 SseEmitter 类来支持 sse

请参阅使用 sse https://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/sse-emitter.html 进行服务器推送的示例

相关内容

最新更新