【发布时间】:2020-01-05 15:19:41
【问题描述】:
我有一个 bean,我在我的 bean 配置中声明如下:
@Configuration
public class BeanConfig {
@Bean
public MemberDTO getMemberDTO() {
return new MemberDTO();
}
}
当用户调用我的服务时,我使用他们提供的用户名和密码来调用不同服务的端点以获取用户的信息:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static final Logger LOGGER = LogManager.getLogger(CustomAuthenticationProvider.class);
private @Autowired MemberDTO memberDTO;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String loginGeniuneFailMessage = "";
boolean loginGeniuneFail = false;
try {
String username = authentication.getName();
String password = authentication.getCredentials().toString();
String endPoint = credentialsBaseUrl + "/api/login";
HttpResponse<MemberDTO> response_auth = Unirest.get(endPoint)
.basicAuth(username, password)
.header("Accept", "*/*")
.asObject(MemberDTO.class);
int status_auth = response_auth.getStatus();
if (status_auth == 200) {
if (response_auth.getBody() == null) {
LOGGER.info("account validation - could not parse response body to object");
UnirestParsingException ex = response_auth.getParsingError().get();
LOGGER.error("parsing error: ", ex);
} else {
memberDTO = response_auth.getBody();
}
}
...
} catch (Exception ex) {
...
}
}
我想将用户的信息存储在 memberDTO 中,并在不同组件的其他地方使用 memberDTO,而不是每次都调用登录 API:
@Component
public class MemberLogic {
private @Autowired MemberDTO memberDTO;
public ResponseEntity<?> processMemberInformation(WrapperDTO wrapperDTO, BindingResult result) {
if (result.hasFieldErrors()) {
String errors = result.getFieldErrors().stream()
.map(p -> p.getDefaultMessage()).collect(Collectors.joining("\n"));
return ResponseEntity.badRequest().body("An error occured while trying to persist information: " + errors);
}
String name = memberDTO.getName();
...
}
}
现在的问题是“memberDTO.getName()”返回 null,即使该值是在 CustomAuthenticationProvider 中的初始 API 调用中设置的。
我的问题是:为什么这不起作用?这是处理此类事情的最佳方法吗?
谢谢。
【问题讨论】:
-
没有使用
SecurityContext的具体原因是什么? -
@chrylis-onstrike- 这与直接问题有关吗?
-
基本上,您正在尝试存储有关登录用户的信息,并在应用程序需要的任何地方使用它。正如@chrylis-onstrike- 建议的那样,最好使用 SecurityContext 来存储登录的用户详细信息。这是在基于 Spring 的应用程序中获取登录用户详细信息的标准方法。
-
@NageswaraRaOMaridu 虽然这是处理用户信息的推荐方式,但它如何回答直接问题:为什么这不起作用?
标签: java spring spring-boot