java - 如何获取活跃用户的 UserDetails

标签 java spring spring-mvc spring-security

在我的 Controller 中,当我需要 Activity (登录)用户时,我正在执行以下操作以获取我的 UserDetails实现:

User activeUser = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
log.debug(activeUser.getSomeCustomField());

它工作正常,但我认为 Spring 在这种情况下可以让生活更轻松。有没有办法让UserDetails自动连接到 Controller 或方法中?

例如,类似于:
public ModelAndView someRequestHandler(Principal principal) { ... }

但不是得到 UsernamePasswordAuthenticationToken , 我得到一个 UserDetails相反?

我正在寻找一个优雅的解决方案。有什么想法吗?

最佳答案

序言:从 Spring-Security 3.2 开始,有一个很好的注释 @AuthenticationPrincipal在这个答案的末尾描述。当您使用 Spring-Security >= 3.2 时,这是最好的方法。

当你:

  • 使用旧版本的 Spring-Security,
  • 需要通过存储在主体或
  • 中的一些信息(如登录名或 ID)从数据库加载自定义用户对象。
  • 想学习如何HandlerMethodArgumentResolverWebArgumentResolver可以优雅的解决这个问题,或者只是想了解一下背后的背景@AuthenticationPrincipalAuthenticationPrincipalArgumentResolver (因为它基于 HandlerMethodArgumentResolver )

  • 然后继续阅读——否则只需使用 @AuthenticationPrincipal感谢 Rob Winch(作者 @AuthenticationPrincipal)和 Lukas Schmelzeisen (他的回答)。

    (顺便说一句:我的回答有点旧(2012 年 1 月),所以 Lukas Schmelzeisen 作为第一个提出的 @AuthenticationPrincipal 基于 Spring Security 3.2 的注释解决方案。)

    然后你可以在你的 Controller 中使用
    public ModelAndView someRequestHandler(Principal principal) {
       User activeUser = (User) ((Authentication) principal).getPrincipal();
       ...
    }
    

    如果你需要它一次就可以了。但是如果你需要它好几次,因为它会用基础设施细节污染你的 Controller ,这通常应该被框架隐藏。

    所以你可能真正想要的是有一个这样的 Controller :
    public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
       ...
    }
    

    因此你只需要实现一个 WebArgumentResolver .它有一个方法
    Object resolveArgument(MethodParameter methodParameter,
                       NativeWebRequest webRequest)
                       throws Exception
    

    这将获取 Web 请求(第二个参数)并且必须返回 User如果它感觉对方法参数(第一个参数)负责。

    从 Spring 3.1 开始,有一个名为 HandlerMethodArgumentResolver 的新概念。 .如果您使用 Spring 3.1+,那么您应该使用它。 (在此答案的下一部分中对此进行了描述))
    public class CurrentUserWebArgumentResolver implements WebArgumentResolver{
    
       Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
            if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
               Principal principal = webRequest.getUserPrincipal();
               return (User) ((Authentication) principal).getPrincipal();
            } else {
               return WebArgumentResolver.UNRESOLVED;
            }
       }
    }
    

    您需要定义自定义注释——如果 User 的每个实例都应始终从安全上下文中获取,但绝不是命令对象,则可以跳过它。
    @Target(ElementType.PARAMETER)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface ActiveUser {}
    

    在配置中,您只需要添加以下内容:
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
        id="applicationConversionService">
        <property name="customArgumentResolver">
            <bean class="CurrentUserWebArgumentResolver"/>
        </property>
    </bean>
    

    @见:Learn to customize Spring MVC @Controller method arguments

    应该注意的是,如果您使用的是 Spring 3.1,他们建议使用 HandlerMethodArgumentResolver 而不是 WebArgumentResolver。 - 见杰伊的评论

    HandlerMethodArgumentResolver 相同适用于 Spring 3.1+
    public class CurrentUserHandlerMethodArgumentResolver
                                   implements HandlerMethodArgumentResolver {
    
         @Override
         public boolean supportsParameter(MethodParameter methodParameter) {
              return
                  methodParameter.getParameterAnnotation(ActiveUser.class) != null
                  && methodParameter.getParameterType().equals(User.class);
         }
    
         @Override
         public Object resolveArgument(MethodParameter methodParameter,
                             ModelAndViewContainer mavContainer,
                             NativeWebRequest webRequest,
                             WebDataBinderFactory binderFactory) throws Exception {
    
              if (this.supportsParameter(methodParameter)) {
                  Principal principal = webRequest.getUserPrincipal();
                  return (User) ((Authentication) principal).getPrincipal();
              } else {
                  return WebArgumentResolver.UNRESOLVED;
              }
         }
    }
    

    在配置中,需要添加这个
    <mvc:annotation-driven>
          <mvc:argument-resolvers>
               <bean class="CurrentUserHandlerMethodArgumentResolver"/>         
          </mvc:argument-resolvers>
     </mvc:annotation-driven>
    

    @见 Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface

    Spring-Security 3.2解决方案

    Spring Security 3.2(不要与 Spring 3.2 混淆)有自己的内置解决方案: @AuthenticationPrincipal ( org.springframework.security.web.bind.annotation.AuthenticationPrincipal ) 。这在 Lukas Schmelzeisen`s answer 中有很好的描述

    这只是写
    ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
        ...
     }
    

    要使其正常工作,您需要注册 AuthenticationPrincipalArgumentResolver ( org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver ) : 要么通过“激活”@EnableWebMvcSecurity或者通过在 mvc:argument-resolvers 中注册这个 bean - 与我在上面使用可能的 Spring 3.1 解决方案描述它的方式相同。

    @见 Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal

    Spring-Security 4.0解决方案

    它的工作原理类似于 Spring 3.2 解决方案,但在 Spring 4.0 中 @AuthenticationPrincipalAuthenticationPrincipalArgumentResolver被“移动”到另一个包:
  • org.springframework.security.core.annotation.AuthenticationPrincipal
  • org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver

  • (但是旧包中的旧类仍然存在,所以不要混合它们!)

    这只是写
    import org.springframework.security.core.annotation.AuthenticationPrincipal;
    ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
        ...
    }
    

    要使其正常工作,您需要注册 ( org.springframework.security.web.method.annotation. ) AuthenticationPrincipalArgumentResolver :通过“激活”@EnableWebMvcSecurity或者通过在 mvc:argument-resolvers 中注册这个 bean - 与我在上面使用可能的 Spring 3.1 解决方案描述它的方式相同。
    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
        </mvc:argument-resolvers>
    </mvc:annotation-driven>
    

    @见 Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal

    关于java - 如何获取活跃用户的 UserDetails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8764545/

    相关文章:

    java - 平板电脑和手机之间的应用程序小部件大小不一致

    java - Spring Boot - 在部署时启动后台线程的最佳方式

    spring - Java-jar文件的Spring属性文件配置

    java - 如何正确使用 Spring MVC <form :select> tag to show the value of a specific object field into a collection?

    java - Struts2 - 通过带有动态参数的注释转发

    java - 使用jsp将递归结构转换为xml

    hibernate - Spring Mvc Controller - 删除问题

    spring-mvc - 将请求 header 传递给 Ribbon IRule 关键参数

    java - 使用默认程序运行文件并等待编辑结束

    java - 为每个新请求创建新的 java.sql.Connection