gpt4 book ai didi

java - Spring:通过注入(inject)获取当前用户

转载 作者:行者123 更新时间:2023-11-29 04:29:25 26 4
gpt4 key购买 nike

目前我正在用通常的方式吸引用户

SecurityContextHolder.getContext().getAuthentication().getPrincipal

不知是否可以通过bean factory获取,像这样

@Service
class UserProvider implements BeanFactoryAware {
BeanFactory beanFactory;

public Principal get(){
return (Principal) beanFactory.getBean("Principal");
}

@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}

Spring 是否存储包含当前经过身份验证的用户的 session 范围的 bean?

最佳答案

您可以将自定义 bean 后处理器与动态代理结合使用来实现此目的。

类似于:

@SpringBootApplication
public class So44435897Application {

public static void main(String[] args) {
SpringApplication.run(So44435897Application.class, args);
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface ApplicationUser { }

@Component
public static class CurrentUserBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), field -> {
ReflectionUtils.makeAccessible(field);
if (field.getAnnotation(ApplicationUser.class) != null) {
final Object proxyInstance = Proxy.newProxyInstance(bean.getClass().getClassLoader(),
new Class[] { UserDetails.class }, (proxy, method, args) -> {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.isAuthenticated()) {
final Object principal = authentication.getPrincipal();
return method.invoke(principal, args);
}
throw new NullPointerException();
});
field.set(bean, proxyInstance);
}
});
return bean;
}

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}

@RestController
public static class HomeController {
final UserService userService;

@Autowired
public HomeController(UserService userService) {
this.userService = userService;
}

@GetMapping
public String me() {
return userService.getName();
}
}

@Service
public static class UserService {
@ApplicationUser
UserDetails user;

String getName() {
return user.getUsername();
}
}
}

=>

$ curl -u admin:admin -XGET 'localhost:8080'
admin%

关于java - Spring:通过注入(inject)获取当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44435897/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com