如何使用经过身份验证的用户信息初始化服务bean

问题描述 投票:0回答:2

我有一个与当前经过身份验证的用户紧密耦合的服务。它应该以某种方式从更高的上下文(控制器)接收

userId
作为参数。该服务无法从任何全局可用的“auth”上下文访问
userId
,它必须作为参数接收。

服务也需要是一个bean(@Service),因此它应该由Spring自动初始化。

实现这一目标的一种方法如下:

  1. 初始化服务无需
    userId
  2. 然后将
    userId
    传递给服务上调用的每个方法:
@Service
class MyService
  public void method1(int userId) {
    // do something with userId
  }

  public void method2(int userId) {
    // do something with userId
  }
end

// Usage
myService = new MyService(); // This is done by Spring (with no problem).
myService.method1(getUserIdFromAnyAuthContext())
myService.method2(getUserIdFromAnyAuthContext())

我希望我的服务工作的方式(如果它不是 bean)如下:

@Service
class MyService
  private int currentUserId;

  public MyService(int currentUserId) {
    this.currentUserId = currentUserId;
  }

  public void method1() {
    // do something with currentUserId
  }

  public void method2() {
    // do something with currentUserId
  }
end

// Usage
myService = new MyService(getUserIdFromAnyAuthContext()); // I want Spring to be able to do it and have MyService as a bean.
myService.method1()
myService.method2()

上面的例子展示了如果它不是一个bean我会如何做。重点是不要将

userId
传递给每个方法。它应该在每个请求上以某种方式注入到服务中,但同时它应该就像我以标准 Java 方式传递它一样,因此可以独立于外部上下文进行测试。

如何将服务作为 bean 并使用“auth”数据对其进行初始化?

在重要的情况下(回复@Anish B. 评论):我将使用 Spring Security 作为身份验证提供者。但请注意,服务本身无法访问任何全局可用的“auth”上下文,它应该独立于外部上下文。

java spring spring-mvc spring-security inversion-of-control
2个回答
0
投票

Spring Security 创建一个包含当前用户信息的身份验证 bean。如果你想摆脱对Spring Security的依赖,只需使用Principal接口,它是Authentication的父接口。

@Service
class MyService
 
  private final Principal principal;

  public MyService(Principal principal) {
    this.principal = principal;
  }
}

0
投票

如果你想要 Spring Security,你可以这样做。

import org.springframework.security.core.Authentication;

@Service
class MyService
 
  private Authentication Authentication;

  public MyService(Authentication authentication) {
    this.authentication = authentication;
  }
}

// usage
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;

SecurityContext context = SecurityContextHolder.getContext();
MyService myService = new MyService(context.getAuthentication());

注意:

Authentication
来自 Spring Security 的类拥有经过身份验证的用户/主体的所有详细信息。 Spring 将通过
SecurityContext
使用经过身份验证的用户信息初始化服务 bean。

请参阅

SecurityContext.getAuthentication()
JavaDocs 了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.