Spring Security中始终拒绝访问 - DenyAllPermissionEvaluator

Has*_*ral 19 java spring acl spring-security spring-boot

我在Spring Boot应用程序中配置了ACL.ACL配置如下:

@Configuration
@ComponentScan(basePackages = "com.company")
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ACLConfigration extends GlobalMethodSecurityConfiguration {

    @Autowired
    DataSource dataSource;

    @Bean
    public EhCacheBasedAclCache aclCache() {
        return new EhCacheBasedAclCache(aclEhCacheFactoryBean().getObject(), permissionGrantingStrategy(), aclAuthorizationStrategy());
    }

    @Bean
    public EhCacheFactoryBean aclEhCacheFactoryBean() {
        EhCacheFactoryBean ehCacheFactoryBean = new EhCacheFactoryBean();
        ehCacheFactoryBean.setCacheManager(aclCacheManager().getObject());
        ehCacheFactoryBean.setCacheName("aclCache");
        return ehCacheFactoryBean;
    }

    @Bean
    public EhCacheManagerFactoryBean aclCacheManager() {
        return new EhCacheManagerFactoryBean();
    }

    @Bean
    public DefaultPermissionGrantingStrategy permissionGrantingStrategy() {
        ConsoleAuditLogger consoleAuditLogger = new ConsoleAuditLogger();
        return new DefaultPermissionGrantingStrategy(consoleAuditLogger);
    }

    @Bean
    public AclAuthorizationStrategy aclAuthorizationStrategy() {
        return new AclAuthorizationStrategyImpl(new SimpleGrantedAuthority("ROLE_ACL_ADMIN"));
    }

    @Bean
    public LookupStrategy lookupStrategy() {
        return new BasicLookupStrategy(dataSource, aclCache(), aclAuthorizationStrategy(), new ConsoleAuditLogger());
    }

    @Bean
    public JdbcMutableAclService aclService() {
        return new JdbcMutableAclService(dataSource, lookupStrategy(), aclCache());
    }

    @Bean
    public DefaultMethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler() {
        return new DefaultMethodSecurityExpressionHandler();
    }

    @Override
    public MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = defaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
        expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
        return expressionHandler;
    }
}
Run Code Online (Sandbox Code Playgroud)

参考文献:

安全配置如下:

@Configuration
@EnableWebSecurity
public class CustomSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public AuthenticationEntryPoint entryPoint() {
        return new LoginUrlAuthenticationEntryPoint("/authenticate");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/authenticate/**").permitAll()
                .anyRequest().fullyAuthenticated()
                .and().requestCache().requestCache(new NullRequestCache())
                .and().addFilterBefore(authenticationFilter(), CustomUsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
    }

    @Bean
    public CustomUsernamePasswordAuthenticationFilter authenticationFilter()
            throws Exception {
        CustomUsernamePasswordAuthenticationFilter authenticationFilter = new CustomUsernamePasswordAuthenticationFilter();
        authenticationFilter.setUsernameParameter("username");
        authenticationFilter.setPasswordParameter("password");
        authenticationFilter.setFilterProcessesUrl("/authenticate");
        authenticationFilter.setAuthenticationSuccessHandler(new CustomAuthenticationSuccessHandler());
        authenticationFilter.setAuthenticationFailureHandler(new CustomAuthenticationFailureHandler());
        authenticationFilter.setAuthenticationManager(authenticationManagerBean());
        return authenticationFilter;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
Run Code Online (Sandbox Code Playgroud)

我的CustomAuthenticationProvider班级:

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UsersService usersService;

    @Override
    public Authentication authenticate(Authentication authentication)
            throws AuthenticationException {

        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = usersService.findOne(username);

        if(user != null && usersService.comparePassword(user, password)){

            return new UsernamePasswordAuthenticationToken(
                    user.getUsername(),
                    user.getPassword(),
                    AuthorityUtils.commaSeparatedStringToAuthorityList(
                            user.getUserRoles().stream().collect(Collectors.joining(","))));
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的CustomUsernamePasswordAuthenticationToken:

public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {

        if(!request.getMethod().equals("POST"))
            throw new AuthenticationServiceException(String.format("Authentication method not supported: %s", request.getMethod()));

        try {

            CustomUsernamePasswordAuthenticationForm form = new ObjectMapper().readValue(request.getReader(), CustomUsernamePasswordAuthenticationForm.class);

            String username = form.getUsername();
            String password = form.getPassword();

            if(username == null)
                username = "";

            if(password == null)
                password = "";

            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);

            setDetails(request, token);

            return getAuthenticationManager().authenticate(token);

        } catch (IOException exception) {
            throw new CustomAuthenticationException(exception);
        }
    }

    private class CustomAuthenticationException extends RuntimeException {
        private CustomAuthenticationException(Throwable throwable) {
            super(throwable);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

除了以上的,我有CustomAuthenticationFailureHandler,CustomAuthenticationSuccessHandler,CustomNoRedirectStrategyCustomUsernamePasswordAuthenticationForm我跳过这个问题的长度的缘故.

我正在使用可在此处找到的MySQL架构.

我正在为我的acl相关表添加条目,如下所示:

INSERT INTO acl_class VALUES (1, com.company.project.domain.users.User)
INSERT INTO acl_sid VALUES (1, 1, "demo")
Run Code Online (Sandbox Code Playgroud)

(我有一个用户名用户demo)

INSERT INTO acl_object_identity VALUES (1, 1, 1, NULL, 1, 0)
INSERT INTO acl_entry VALUES (1, 1, 1, 1, 1, 1, 1, 1)
Run Code Online (Sandbox Code Playgroud)

但我得到的只是:

Denying user demo permission 'READ' on object com.company.project.domain.users.User@4a49e9b4
Run Code Online (Sandbox Code Playgroud)

在我的

@PostFilter("hasPermission(filterObject, 'READ')")
Run Code Online (Sandbox Code Playgroud)

我怀疑这里有几个问题:

  1. hasPermission表达式:我与"读"和取代它"1",但没有的程度.
  2. 我的数据库条目不对
  3. 我没有实现自定义权限评估程序.这是必需的还是expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));足够的?

更新

使用的样本方法@PostFilter:

@RequestMapping(method = RequestMethod.GET)
    @PostFilter("hasPermission(filterObject, 'READ')")
    List<User> find(@Min(0) @RequestParam(value = "limit", required = false, defaultValue = "10") Integer limit,
                    @Min(0) @RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
                    @RequestParam(value = "email", required = false) String email,
                    @RequestParam(value = "firstName", required = false) String firstName,
                    @RequestParam(value = "lastName", required = false) String lastName,
                    @RequestParam(value = "userRole", required = false) String userRole) {

        return usersService.find(
                limit,
                page,
                email,
                firstName,
                lastName,
                userRole);
    }
Run Code Online (Sandbox Code Playgroud)

更新#2:

现在的问题反映了在身份验证/授权/ ACL方面设置的所有内容.

更新#3:

我现在非常接近解决这个问题,唯一剩下的就是解决这个问题:

/sf/ask/3009760561/

如果有人能帮助我解决这个问题,我终于可以写一下我已经解决的问题.

s_b*_*ead 6

我升级了我的应用程序以使用Spring Security 4.2.1.RELEASE然后我开始在所有带@PreAuthorize注释的方法中遇到意外访问被拒绝,这在升级之前工作正常.我调试了spring安全代码,我意识到问题是要检查的所有角色都带有一个默认字符串"ROLE_",无论我将默认前缀设置为空,如下面的代码所示.

auth.ldapAuthentication()
        .groupSearchBase(ldapProperties.getProperty("groupSearchBase"))
        .groupRoleAttribute(ldapProperties.getProperty("groupRoleAttribute"))
        .groupSearchFilter(ldapProperties.getProperty("groupSearchFilter"))

        //this call used to be plenty to override the default prefix
        .rolePrefix("")

        .userSearchBase(ldapProperties.getProperty("userSearchBase"))
        .userSearchFilter(ldapProperties.getProperty("userSearchFilter"))
        .contextSource(this.ldapContextSource);
Run Code Online (Sandbox Code Playgroud)

我的所有控制器方法都注释了@PreAuthorize("hasRole('my_ldap_group_name')"),但是,框架没有考虑我的空角色前缀设置,因此它使用ROLE_my_ldap_group_name来检查实际角色.

在我深入研究框架的代码之后,我意识到该类org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler仍然设置了默认角色前缀"ROLE_".我跟踪了它的值的来源,我发现它首先检查类的声明bean,以便在bean的org.springframework.security.config.core.GrantedAuthorityDefaults第一次初始化期间查找默认前缀org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer,但是,因为这个初始化bean无法找到它声明的,所以最终使用上述默认前缀.

我相信这不是预期的行为:Spring Security应该从ldapAuthentication考虑相同的rolePrefix,但是,为了解决这个问题,有必要将bean添加org.springframework.security.config.core.GrantedAuthorityDefaults到我的应用程序上下文(我使用基于注释的配置),如下:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CesSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String ROLE_PREFIX = "";
    //... ommited code ...
    @Bean
    public GrantedAuthorityDefaults grantedAuthorityDefaults() {
        return new GrantedAuthorityDefaults(ROLE_PREFIX);
    }

}
Run Code Online (Sandbox Code Playgroud)

也许你遇到了同样的问题 - 我可以看到你正在使用DefaultMethodSecurityExpressionHandler并且它也使用bean GrantedAuthorityDefaults,所以如果你使用的是与我相同的Spring Security版本 - 4.2.1.RELEASE你可能会遇到同样的问题.


Has*_*ral 5

这是期待已久的答案:

文件清楚地描述:

要使用 hasPermission() 表达式,您必须在应用程序上下文中显式配置 PermissionEvaluator。这看起来像这样:

所以基本上我在做我的AclConfiguration延伸GlobalMethodSecurityConfiguration

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new AclPermissionEvaluator(aclService()));
        expressionHandler.setPermissionCacheOptimizer(new AclPermissionCacheOptimizer(aclService()));
        return expressionHandler;
    }
Run Code Online (Sandbox Code Playgroud)

哪个没有被 Spring 处理!

我不得不分开AclConfigGlobalMethodSecurityConfiguration。当@Bean后者定义了 s 时,上述方法没有得到处理,这可能是一个错误(如果没有,欢迎对主题进行任何澄清)。