Spring Security 在非托管类中使用Spring应用程序属性

mnowg1ta  于 2023-10-20  发布在  Spring
关注(0)|答案(2)|浏览(106)

我正在使用Sping Boot 3.1.2,并定义了一个自定义的SecurityExpressionRoot来处理授权过程。
然而,我有一些值作为环境变量存储,它们通过application.properties引用:

myapp.home-org=${HOME_ORG_ID}

它们通常在应用中通过自动装配定义它们的配置类来使用:

@Getter
@Setter
@Configuration
@ConfigurationProperties(prefix = "myapp")
public class EnvironmentConfig {

    /**
     * UUID of the organization users are originating from.
     */
    private UUID homeOrg;

}

我正在寻找一种方法来使用SecurityExpressionRoot中的变量作为授权决策的基础。
最好的办法是什么?

wecizke3

wecizke31#

可以通过继承Spring Class ApplicationContextAwareBeanFactoryPostProcessor静态获取属性值:

@Component
public class SpringUtil implements  BeanFactoryPostProcessor,ApplicationContextAware {  
    /**
     * Spring beanFactory
     */
    private static ConfigurableListableBeanFactory beanFactory;
    /**
     * Spring context
     */
    private static ApplicationContext applicationContext;

    @SuppressWarnings("NullableProblems")
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtil.beanFactory = beanFactory;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringUtil.applicationContext = applicationContext;
    }

    /**
     * get {@link ApplicationContext}
     *
     * @return {@link ApplicationContext}
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
   /**
     * get {@link ListableBeanFactory},is {@link ConfigurableListableBeanFactory} or {@link ApplicationContextAware}
     *
     * @return {@link ListableBeanFactory}
     * @since 5.7.0
     */
    public static ListableBeanFactory getBeanFactory() {
        return null == beanFactory ? applicationContext : beanFactory;
    }
    /**
     * by class get bean
     *
     * @param <T>   Bean type
     * @param clazz Bean class
     * @return Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        return getBeanFactory().getBean(clazz);
    }
    /**
     *  get property value
     *
     * @param  property key
     * @return property value
     */
    public static String getProperty(String key) {
        if (null == applicationContext) {
            return null;
        }
        return applicationContext.getEnvironment().getProperty(key);
    }
}

获取属性:String value=SpringUtil.getProperty("myapp.home-org");UUID value=SpringUtil.getBean(EnvironmentConfig.class).getHomeOrg();

o8x7eapl

o8x7eapl2#

你可以定义一个“initializer”类,它将保存初始化你的自定义类所需的配置,如3)中定义的:https://www.baeldung.com/inject-properties-value-non-spring-class.2)也可以,但我发现初始化器解决方案比使用类加载器更优雅。

相关问题