微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

@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).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐