Если кто-то все еще изучает, как обновить полномочия другого пользователя, не заставляя этого пользователя повторно проходить аутентификацию, вы можете попытаться добавить перехватчик, который перезагружает аутентификацию. Это обеспечит постоянное обновление ваших полномочий.
Однако - из-за дополнительного перехватчика произойдет некоторое снижение производительности (например, если вы получите свои пользовательские роли из вашей базы данных, она будет запрашиваться для каждого HTTP-запроса).
@Component
public class VerifyAccessInterceptor implements HandlerInterceptor {
// ...
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Set<GrantedAuthority> authorities = new HashSet<>();
if (auth.isAuthenticated()) {
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
}
User userFromDatabase = getUserFromDatabase(auth.getName());
if (userFromDatabase != null) {
// add whatever authorities you want here
authorities.add(new SimpleGrantedAuthority("..."));
}
Authentication newAuth = null;
if (auth.getClass() == OAuth2AuthenticationToken.class) {
OAuth2User principal = ((OAuth2AuthenticationToken)auth).getPrincipal();
if (principal != null) {
newAuth = new OAuth2AuthenticationToken(principal, authorities,(((OAuth2AuthenticationToken)auth).getAuthorizedClientRegistrationId()));
}
}
SecurityContextHolder.getContext().setAuthentication(newAuth);
return true;
}
}
Эта конкретная реализация использует OAuth2 (OAuth2AuthenticationToken
), но вы можете использовать UsernamePasswordAuthenticationToken
вместо.
А теперь, чтобы добавить ваш перехватчик в конфигурацию:
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {
@Autowired
private VerifyAccessInterceptor verifyAccessInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(verifyAccessInterceptor).addPathPatterns("/**");
}
}
Я также сделал статью об этом .