java - Spring Security - 在 Controller 中获取登录用户 - 礼貌

标签 java spring spring-mvc spring-security

我正在使用 Spring (4.0.2)、Spring @MVC (4.0.2) 和 Spring Security (3.2.5) 开发我的第一个应用程序。我现在可以使用 Spring Security 成功登录,但现在我想到了一个“良好实践”问题:

目前我已经实现了我自己的 UserDetailsUserDetailsS​​ervice 版本,以保存从数据库中获取的详细信息。

获取 UserDetails 的最佳方式(更简洁)是什么?

到目前为止,我正在使用这两种选择:

  1. 使用方法中的下一行代码

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    
  2. 在方法中添加参数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/

相关文章:

java - 使用 spring mvc 下载的 Xlsx 文件已损坏且内容类型已更改

java - 我可以在机器上同时安装Maven和Gradle吗

java - 服务器浏览器如何在游戏工作中?

java - Spring boot Resource getFile() 不起作用

java - 导入 Maven 插件

java - 独立使用 JdbcTemplate

java - 如何将 url id 映射到服务器上的内容?

java - 在 neo4j 中制作任意标识符

java - Spring mvc Controller jsr 303基本列表验证

java - ReSTLet 响应类型