1

I created a custom security expression in order to check if a specific user is allowed to access a resource. So my class extends SecurityExpressionRoot and implements MethodSecurityExpressionOperations. Everything is working fine but I can"t auto-wire spring component, it's null.

 public class CustomWebSecurityExpressionRoot extends SecurityExpressionRoot
        implements MethodSecurityExpressionOperations {
    @Autowired
    private SecurityService securityService;

    public CustomWebSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    public boolean canAccess(Integer accessId) {
        MLoginDto login = securityService.findLoggedInUser();
        return login.getAccess() != null && login.getAccess().contains(accessId);
    } 
}

SecurityService

@Service
@Transactional
public class SecurityServiceImpl implements SecurityService {

    @Override
    public MLoginDto findLoggedInUser() {
        SecurityDetails userDetails = (SecurityDetails) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();

        if (userDetails != null) {
            return userDetails.getLogin();
        }
        return null;
    }

}
karthik selvaraj
  • 426
  • 5
  • 12
  • It isn't controlled by Spring and as such will not be autowired. It isn't recommended anymore to create custom/extended expression roots. Instead create a bean with a method that does what you want and call it using `@yourBean.someMethod` in the Security SpEL expression. – M. Deinum Dec 05 '19 at 12:14
  • @M.Deinum thanks for your quick replay, I got another workaround [here](https://stackoverflow.com/a/55196063/5690546) in future it will help someone – karthik selvaraj Dec 05 '19 at 12:24

0 Answers0