2014-03-27 24 views
6

usign Spring Security,我試圖從我的CustomUserDetailsS​​ervice上的loadUserByUsername方法返回的CustomUser實例中獲取用戶標識,就像我要獲取名稱(get.Name ())與身份驗證。感謝您的任何提示!如何從CustomUser獲取用戶ID在Spring Security

這是我如何得到登陸用戶的當前名稱:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
String name = authentication.getName(); 

這是CustomUser

public class CustomUser extends User 
{ 

private final int userID; 




public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, 
        boolean credentialsNonExpired, 
        boolean accountNonLocked, 
        Collection<? extends GrantedAuthority> authorities, int userID) 
{ 
    super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); 
    this.userID = userID; 
} 
} 

而且我的服務

​​

回答

12
Authentication authentication = ... 
CustomUser customUser = (CustomUser)authentication.getPrincipal(); 
int userId = customUser.getUserId(); 
的loadUserByUsername方法

您必須添加getUserId() getter方法,如果你還沒有它。

+0

工作就像一個魅力!謝謝 –

+2

'Principal'可以被注入。 – naXa

+3

通過方法參數注入:@AuthenticationPrincipal CustomUser customUser – Tom

相關問題