在本文中,我们将向您展示三种在Spring Security中获取当前登录用户名的方法。
1. SecurityContextHolder + Authentication.getName()
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printUser(ModelMap model) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
model.addAttribute("username", name);
return "hello";
}
//...
2. SecurityContextHolder + User.getUsername()
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printUser(ModelMap model) {
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername(); //get logged in username
model.addAttribute("username", name);
return "hello";
}
//...
3. UsernamePasswordAuthenticationToken
这是一种更优雅的解决方案,在运行时中,Spring会将UsernamePasswordAuthenticationToken
注入到Principal
接口中。
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/login", method = RequestMethod.GET)
public String printWelcome(ModelMap model, Principal principal ) {
String name = principal.getName(); //get logged in username
model.addAttribute("username", name);
return "hello";
}
//...
下载源代码
下载它– Spring-Security-Get-Logged-In-Username.zip (9 KB)
参考文献
标签: Spring安全
翻译自: https://mkyong.com/spring-security/get-current-logged-in-username-in-spring-security/