我使用以下配置创建了Spring Boot应用程序:
我的项目中有一个AuditConfiguration
类,如下所示:
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class AuditConfiguration {
@Bean
public AuditorAware<String> auditorProvider() {
return new AuditorAwareImpl();
}
class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Principal principal =
SecurityContextHolder.getContext().getAuthentication();
return Optional.of(principal.getName());
}
}
}
和SecurityContextHolder.getContext().getAuthentication()
始终返回anonymousUser
。
但是,以下代码返回正确的用户名。
@RestController
@RequestMapping("/history")
public class HistoryEndpoint {
@RequestMapping(value = "/username", method = RequestMethod.GET)
@ResponseBody
public String currentUserName(Principal principal) {
return principal.getName();
}
}
我需要您的帮助来解决此问题。
答案 0 :(得分:0)
我使用以下课程获得了认证用户。我在JPA审核方面遇到问题。
@CreatedBy始终保存null
。然后我尝试使用这种方法来获取经过身份验证的用户SecurityContextHolder.getContext().getAuthentication()
。该方法返回了annonymousUser
。但是我的问题已解决。
@ManagedBean
@EnableJpaAuditing
public class SpringSecurityAuditorAware implements AuditorAware<String> {
private final HttpServletRequest httpServletRequest;
public SpringSecurityAuditorAware(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(httpServletRequest.getUserPrincipal())
.map(Principal::getName);
}
}