具有CustomPermissionEvaluator的MethodSecurity不适用于SpringSecurity

时间:2018-08-30 11:14:54

标签: java spring-security

我正在为自己的Spring Security配置而苦苦挣扎,到目前为止,我还无法使其正常运行。需要您的帮助。

这是我的配置:

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

    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        DefaultMethodSecurityExpressionHandler expressionHandler =
                new DefaultMethodSecurityExpressionHandler();
        expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator());
        return expressionHandler;
    }
}

这是CustomPermissionEvaluator

public class CustomPermissionEvaluator implements PermissionEvaluator {

    @Override
    public boolean hasPermission(Authentication auth, Object targetDomainObject, Object permission) {
        return true;
    }

    @Override
    public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
        return true;
    }
}

这是控制者:

@PreAuthorize("hasPermission(#test, 'write')")
@PostMapping("/test")
public Result saveTest(@RequestBody Test test) {
    return Result.build();
}

一切看起来都很简单,但是当我请求其余的API时,出现以下异常:

.m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

任何人都可以给我提示该怎么做?谢谢〜

1 个答案:

答案 0 :(得分:0)

错误是指缺少Authentication对象而不是Authorization对象。您是否定义了UserDetailsService并确定身份验证成功?

对于每个this blog,您可以通过定义获取AuthenticationManagerBuilder的方法来连接userDetailService。在此构建器上,您可以定义一个简单的inMemoryAuthentication进行测试,或者连接AuthenticationProviderUserDetailService的实现。