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

kaz*_*eel 1 java spring spring-mvc spring-security

我正在使用Spring(4.0.2),Spring @MVC(4.0.2)和Spring Security(3.2.5)开发我的第一个应用程序.我现在能够使用Spring Security成功登录,但现在我想到了一个"好的做法"问题:

目前,我HACE实现我自己的版本,UserDetails并且UserDetailsService为了节省从数据库中获取的细节.

获得最佳方式(清洁剂)是哪种UserDetails

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

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

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    
    Run Code Online (Sandbox Code Playgroud)
  2. Authentication auth在方法中添加参数和下一行

    User user = ((CurrentUserDetails) auth.getPrincipal()).getCurrentUser();
    
    Run Code Online (Sandbox Code Playgroud)

我的印象是我弄脏了代码.你不这么认为吗?

Pav*_*ral 5

在我参与的每个项目中,我们总是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;
}
Run Code Online (Sandbox Code Playgroud)

这个课通常坐在{projectPackage}.core.security包里.只要任何代码需要访问当前用户,它就会调用此类.

此外,我们永远不会让控制器层告诉服务层任何有关身份验 服务层(甚至是Hibernate事件侦听器)总是询问SecurityUtils当前的身份验证.