我从这个答案中找到了实现这一目标的方法。我建立HttpSessionSecurityContextRepository
@Bean
public ReloadUserPerRequestHttpSessionSecurityContextRepository userDetailContextRepository() {
return new ReloadUserPerRequestHttpSessionSecurityContextRepository();
}
并将其从asHttpSecurity
类中添加到我的WebSecurityConfigurerAdapter
.and()
.csrf()
.csrfTokenRepository(csrfTokenRepository())
.and()
.securityContext()
.securityContextRepository(userDetailContextRepository())
以下是在每个请求中获取更新的用户信息的示例代码。您可以从您的 API 服务器或user-info-url
您的 oauth2 配置中获取。
public class ReloadUserPerRequestHttpSessionSecurityContextRepository extends HttpSessionSecurityContextRepository {
@Override
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
SecurityContext context = super.loadContext(requestResponseHolder);
Authentication auth = context.getAuthentication();
if (auth != null && auth instanceof OAuth2Authentication) {
OAuth2Authentication oldAuth = (OAuth2Authentication) auth;
if (oldAuth.getPrincipal() instanceof LinkedHashMap) {
createNewUserDetailsFromPrincipal(oldAuth.getPrincipal());
}
context.setAuthentication(oldAuth);
}
return context;
}
@SuppressWarnings("unchecked")
private void createNewUserDetailsFromPrincipal(Object principal) {
LinkedHashMap<String, Object> userDetailInfo = (LinkedHashMap<String, Object>) principal;
// fetch User informations from your API server or your database or
// 'user-info-url' of oauth2 endpoint
userDetailInfo.put("name", "EDITED_USER_NAME");
}
}