我正在使用 Spring (4.0.2)、Spring @MVC (4.0.2) 和 Spring Security (3.2.5) 开发我的第一个应用程序。我现在可以使用 Spring Security 成功登录,但现在我想到了一个“良好实践”问题:
目前我已经实现了我自己的 UserDetails
和 UserDetailsService
版本,以保存从数据库中获取的详细信息。
获取 UserDetails
的最佳方式(更简洁)是什么?
到目前为止,我正在使用这两种选择:
使用方法中的下一行代码
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
在方法中添加参数
Authentication auth
和下一行User user = ((CurrentUserDetails) auth.getPrincipal()).getCurrentUser();
我的印象是我弄脏了代码。你不这么认为吗?
最佳答案
在我参与的每个项目中,我们总是至少使用以下方法实现 SecurityUtils
类:
/**
* Get the active authentication object.
* @param strict Whether to throw an exception if no authentication object is found.
* @return Authentication object. Can be null only in non-strict mode.
*/
public static Authentication getAuthentication(boolean strict) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (strict && authentication == null) {
throw new AuthenticationCredentialsNotFoundException("Missing authentication object.");
}
return authentication;
}
/**
* Get active person principal.
* @return Active person principal user. Never null.
* @throws AccessDeniedException in case there is no active person principal.
*/
public static PersonPrincipal getActivePersonPrincipal() {
Object principal = getAuthentication(true).getPrincipal();
if (!(principal instanceof PersonPrincipal)) {
throw new AccessDeniedException("Invalid principal '" + principal + "'.");
}
return (PersonPrincipal) principal;
}
此类通常位于 {projectPackage}.core.security
包中。每当任何代码需要访问当前用户时,它都会调用此类。
此外,我们从不让 Controller 层告诉服务层任何有关身份验证的信息。服务层(甚至 Hibernate 事件监听器)总是询问 SecurityUtils
当前的身份验证。
关于java - Spring Security - 在 Controller 中获取登录用户 - 礼貌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25713315/