I have a "Foo" controller that is autowiring a "Foo" Service.
Now, when I add a PreAuthorize annotation to the controller, the view method works fine and the PreAuthorize tag only grants access to users with the ADMIN authority, but the ResponseBody method (getFoo) does not work as expected.
When using the PreAuthorize annotation, the getFoo method is unable to correctly autowire / instantiate the fooService object, which has a value of null that is causing a NPE (Null Pointer Exception).
Issue overview: fooService is null (causing an NPE) when the getFoo method is called by an AJAX GET request.
However, when commenting out @PreAuthorize, fooService is no longer null when calling getFoo.
...
Here is the code:
Foo Controller
@Controller
@RequestMapping("/foo")
@PreAuthorize("hasAuthority(T(com.foo.security.Authorities).ADMIN)")
public class FooController {
@Autowired
private FooService fooService;
@RequestMapping(value = "/view")
public String view(@AuthenticationPrincipal Principal principal) {
return "view";
}
@RequestMapping(value = "/getFoo")
@ResponseBody
public Foo getFoo() {
fooService.getFoo(); <- NPE happens here
}
}
Foo Service
@Service("fooService")
public class FooServiceImpl implements FooService {
@Autowired
FooRepository fooDao;
@Override
public Foo getFoo() {
return fooDao.getFoo();
}
}
Security Config
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter { ... }
make sure all your controller methods annotated with @RequestMapping
are not declared as private
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With