我正在使用Spring提供的Switch用户过滤器来模拟用户。
如何在SwitchUserFilter中获取正在模拟的原始用户。
我正在做的步骤:
实施例。
1. Log in with User1
2. Impersonting to the User2. (user1 impersonate User2)
3. In Filter I am getting **authentication.getName()** as **User2**
4. While switching back to Original I am getiing **authentication.getName()** as **Null**
现在我需要的是我想在swtichback时获取过滤器中的原始用户( User1 )。
可以吗?
请建议。 让我知道任何人都需要更多的投入。请评论。
提前致谢。
答案 0 :(得分:4)
这是您访问原始用户的方式:
Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (SwitchUserFilter.ROLE_PREVIOUS_ADMINISTRATOR.equals(grantedAuthority.getAuthority())) {
System.out.println(((SwitchUserGrantedAuthority) grantedAuthority).getSource().getPrincipal());
}
}
答案 1 :(得分:0)
在jhipster生成的应用程序的UserJwTController中添加此自定义方法
@PostMapping("/authenticate-externalnodes")
public ResponseEntity<JWTToken> authenticateExternalnodes(@Valid @RequestBody LoginVM loginVM) {
// Get Roles for user via username
Set<Authority> authorities = userService.getUserWithAuthoritiesByLogin(loginVM.getUsername()).get()
.getAuthorities();
// Create Granted Authority Rules
Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
for (Authority authority : authorities) {
grantedAuthorities.add(new SimpleGrantedAuthority(authority.getName()));
}
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
loginVM.getUsername(), "", grantedAuthorities);
Authentication authentication = authenticationToken;
SecurityContextHolder.getContext().setAuthentication(authentication);
boolean rememberMe = (loginVM.isRememberMe() == null) ? false : loginVM.isRememberMe();
String jwt = tokenProvider.createToken(authentication, rememberMe);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
return new ResponseEntity<>(new JWTToken(jwt), httpHeaders, HttpStatus.OK);
}