2016-09-20 42 views
1

成功登錄後,如何在彈簧RestController中檢索登錄的用戶?什麼是通過彈簧安全(angularjs)登錄用戶的正確方法

我使用下面的方法/原理來獲取登錄的用戶,但它檢索anonymousUser而不是登錄的用戶。

Principal principal = SecurityContextHolder.getContext().getAuthentication(); 

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
+0

在這裏,我在我的打印控制檯。 'org.sprin[email protected]905571d8:Principal:anonymousUser;證書:[PROTECTED];已驗證:true;詳細信息:org.sprin[email protected]0:RemoteIpAddress:127.0.0.1; SessionId:0125899A0DC1CF4F5C5A5416E1D1E49C;授予權限:ROLE_ANONYMOUS' – Sadun89

回答

1

您可能會登錄的用戶名從Authentication對象。要獲取用戶對象,可以使用從認證對象中檢索的用戶名。

像這樣的東西應該工作:

Authentication auth = SecurityContextHolder.getContext().getAuthentication(); 
String name = auth.getName(); 
User user = userService.findByUserName(name); 

或者更好的,你可以在你的控制器使用主要作爲參數,並讓春傳遞正確的主要對象。如果用戶未登錄,它將爲空。 Ps:如果您正在獲取匿名身份驗證,則用戶無法通過身份驗證。 SecurityContext返回匿名身份驗證是用戶沒有登錄。 `

+0

'Authentication auth = SecurityContextHolder.getContext()。getAuthentication(); String name = auth.getName();' 檢索「'anonymousUser'」。 – Sadun89

+1

查看我在答案中添加的註釋。 –