Spring @Before更改每个用户登录 [英] Spring @Before changing every user login
问题描述
我有一个@Aspect类,它执行@Before方法并使用用户登录中的一些Id拦截所有查询。但问题是:每次用户登录时,所有登录用户的@Before方法ID都会发生变化,只需要更改当前用户。
I have a @Aspect class, that execute a @Before method and intercept all queries with some Id from the login of user. But the problem is: every time a user make login, the Id from @Before method change for all logged users, it just must to change the current user.
简单的过程:当用户登录时,@ Aspect类获取其id以拦截所有查询。但是这个id正在为每个登录用户而改变。也许应该是会话的问题,我真的不知道。
The simple process: when a user make login, the @Aspect class gets his id to intercept all queries. But this id is changing for every logged user. Maybe should be a problem with session, I really do not know.
方面类:
@Aspect
@Component
@Transactional(propagation = Propagation.REQUIRED)
public class TenancyAspect {
@Autowired
private EntityManager manager;
@Autowired
private AppUserDetailsService appUserDetailsService;
@Before("execution(* com.tc.tcqualidade.repository.*.*(..)) "
+"&& !execution(* com.tc.tcqualidade.repository.UsuarioRepository.porEmailEStatus(..))"
+"&& !execution(* com.tc.tcqualidade.repository.UsuarioRepository.permissoes(..))")
public void definirTenant() {
String tenantid = appUserDetailsService.getTenantId();
if (tenantid != null) {
manager.unwrap(Session.class).enableFilter("tenant").setParameter("id", tenantid);
}
}
}
登录类:
@Service
public class AppUserDetailsService implements UserDetailsService {
private String tenantId = null;
@Autowired
private UsuarioRepository usuarioRepository;
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
Optional<Usuario> usuarioOptional = usuarioRepository.porEmailEStatus(email);
Usuario usuario = usuarioOptional.orElseThrow(() -> new UsernameNotFoundException("Usuário e/ou senha incorretos"));
tenantId = usuario.getEmpresa().getId().toString();
return new UsuarioSistema(usuario, getPermissoes(usuario));
}
private Collection<? extends GrantedAuthority> getPermissoes(Usuario usuario) {
Set<SimpleGrantedAuthority> authorities = new HashSet<>();
List<String> permissoes = usuarioRepository.permissoes(usuario);
permissoes.forEach(p -> authorities.add(new SimpleGrantedAuthority(p.toUpperCase())));
return authorities;
}
public String getTenantId(){
return tenantId;
}
}
推荐答案
使用@Autowired时我看到了同样的行为。 Spring不会在每次访问时创建一个新实例,除非你告诉它这样做,所以对象在所有访问中共享。登录的用户导致所有登录用户更改为该用户的ID。您可能需要将您的一个服务会话限定为:
I've seen this same behaviour when using @Autowired. Spring will not create a new instance on each access unless you tell it do so, so the object is shared across all accesses. A user logging in, caused all logged in users to change to that user's id. You might need to make one of your services session scoped:
@Service
@Scope(value="session", proxyMode= ScopedProxyMode.TARGET_CLASS)
这篇关于Spring @Before更改每个用户登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!