@Autowired in Spring PermissionEvaluator

前端之家收集整理的这篇文章主要介绍了@Autowired in Spring PermissionEvaluator前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

首先,我已经广泛搜索了这个,虽然似乎有一个固定的地方我无法成功引用PermissionEvaluator中注入的@Bean:

https://jira.springsource.org/browse/SEC-2136?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel

在该问题的评论部分,Rob Winch提供了一个解决方案的建议

to work around this issue,you can proxy your permissionEvaluator using LazyInitTargetSource

话虽这么说,我在实现发布的XML的基于注释的JavaConfig版本时遇到了麻烦.我正在使用Spring Boot 1.0.0.BUILD-SNAPSHOT和spring-boot-starter-security.

我有一个类来配置方法安全性,如下所示:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {                   

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {

        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new MyPermissionEvaluator());
        expressionHandler.setParameterNameDiscoverer(new SimpleParameterDiscoverer());

        return expressionHandler;
    }
}

并且PermissionEvaluator的开始:

public class MyPermissionEvaluator implements PermissionEvaluator {

    private static final Logger LOG = LoggerFactory.getLogger(MyPermissionEvaluator.class); 

    @Autowired
    private UserRepository userRepo;    

    @Override
    public boolean hasPermission(Authentication authentication,Object targetDomainObject,Object permission) {     

    if (authentication == null || !authentication.isAuthenticated()) {
        return false;
    }

    if (permission instanceof String) {

        switch((String) permission) {

        case "findUser":
            return handleUserPermission(authentication,targetDomainObject);

        default:
            LOG.error("No permission handler found for permission: " + permission);             
        }           
    }

    return false;
}

@Override
public boolean hasPermission(Authentication authentication,Serializable targetId,String targetType,Object permission) {

    throw new RuntimeException("Id-based permission evaluation not currently supported.");
}

private boolean handleUserPermission(Authentication auth,Object targetDomainObject) {

    if (targetDomainObject instanceof Long) {           

        boolean hasPermission = userRepo.canFind((Long) targetDomainObject);

        return hasPermission;
    }

    return false;
}

}

需要做什么才能从PremissionEvaluator中获取对UserRepository的引用?我尝试了各种变通方法,但没有成功.似乎没有任何东西可以@Autowired到PermissionEvaluator ……

最佳答案
没有任何东西可以自动装入使用new …()创建的对象(除非您使用@Configurable和AspectJ).因此,您几乎肯定需要将PermissionEvaluator拉入@Bean.如果你还需要使它成为一个惰性代理(由于Spring Security初始化的排序敏感性),那么你应该添加@Lazy @Scope(proxyMode = INTERFACES)(如果更适合你,可以添加TARGET_CLASS).
原文链接:/spring/431946.html

猜你在找的Spring相关文章