从客户端调用rest / soap服务时,Spring安全上下文是否持久存在。我有一个客户端应用程序,它使用SecurityContextHolder.getContext()。setAuthentication()设置身份验证。客户端应用程序在需要获取上下文的地方进行休息/肥皂调用。
//Setting security context in client application:
User contextUser = new User(username, enc_password, true, true, true, true,grantedAuthorities, null);
authentication = new UsernamePasswordAuthenticationToken(contextUser, username,grantedAuthorities);
SecurityContextHolder.getContext().setAuthentication(authentication);
// on server side
// I want to get following authentication on server side to get logged in user
Authentication auth=SecurityContextHolder.getContext().getAuthentication();
User user= null;
if (auth != null && !(auth instanceof AnonymousAuthenticationToken)) {
// userDetails = auth.getPrincipal()
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String username = null;
if (principal instanceof UserDetails) {
username = ((UserDetails) principal).getUsername();
user = (UserDetails) principal;
} else {
username = principal.toString();
}
}
答案 0 :(得分:0)
要在服务器端访问username
,请在进行REST / SOAP API调用后,通过在调用API之前在每个请求的标头中添加用户名来实现。
使用Spring Interceptor拦截服务器端的每个请求,您可以通过实现HandlerInterceptorAdapter
接口来创建拦截器类。