Assis
Assis

Reputation: 33

With which methods does @Secured and @PreAuthorize annotation work?

I have the following example:

WhateverController:

@Controller
@RequestMapping(value = "api/whatever")
public class WhateverController {

    @Autowired private WhateverService whateverService;

    @RequestMapping(value = "/list", method = GET)
    @Secured({ "ROLE_WHATEVER_CANSEARCH" })
    @ResponseBody
    public List<WhateverDTO> findList(@RequestParam(value = "values") String[] values) {
        return whateverService.findThings(values);
    }

}

WhateverService:

@Service
public class WhateverService {

    @Autowired private WhateverDAO whateverDAO;

    public List<WhateverDTO> findThings(String[] values) {
        //...
        validate();
        return whateverDAO.findThings(values);
    }

    @Secured({ "ROLE_SPECIFICPERMISSION" }) // Throws AccessDeniedException
    private void validate() {
        if(thing) throw new RuntimeException("You can't...");
    }

}
  1. Would the annotation @Secured work in the method 'validate' on 'WhateverService'?
  2. If it wouldn't, then why?
  3. The same behaviour is applicable for the annotation @PreAuthorize?

Upvotes: 2

Views: 690

Answers (1)

Oreste Viron
Oreste Viron

Reputation: 3805

No, not because it's private, but because Spring-Security is based on Spring-AOP. On Spring-AOP, the call between methods that are in the same classes won't call aspects.

With @Secured annotation, a test is made before the method. If the user hasn't the right roles, an exception is thrown.

@PreAuthorize is practically the same, except it allows more advanced behavior.

You can also configure security using WebSecurityConfigurerAdapter. And do not forget to enable the Pre/post annotations with @EnableGlobalMethodSecurity(prePostEnabled = true)

Upvotes: 7

Related Questions