Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowired Service is Null in ResponseBody method when using PreAuthorize

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 { ... }
like image 732
Kyle Avatar asked Jan 11 '17 17:01

Kyle


1 Answers

make sure all your controller methods annotated with @RequestMapping are not declared as private

like image 153
yod Avatar answered Oct 27 '22 20:10

yod