0

I'm injecting @AuthenticationPrincipal in a @RestController method. It works as expected in the JVM, but I get a NPE at security SpEL evaluation when running native image.

Here is the method:

    @PutMapping("/{proxiedUserSubject}/proxies/{grantedUserSubject}")
    @PreAuthorize("#token.subject == #proxiedUserSubject")
    public ResponseEntity<?> editUserProxy(
            @PathVariable(name = "proxiedUserSubject") @NotEmpty String proxiedUserSubject,
            @PathVariable(name = "grantedUserSubject") @NotEmpty String grantedUserSubject,
            @RequestBody Collection<Long> grantIds,
            @AuthenticationPrincipal Object token) {

        final var proxiedUser = getOrCreateUser(proxiedUserSubject);
        final var grantedUser = getOrCreateUser(grantedUserSubject);
        final var grants = grantRepo.findAllById(grantIds);
        grantedUser.setGrantsOn(proxiedUser, grants);
        userRepo.save(grantedUser);

        return ResponseEntity.accepted().build();
    }

Any idea why token is null in native image only? I suspect something with AOT plugin configuration, but could not isolate the issue yet.

ch4mp
  • 6,622
  • 6
  • 29
  • 49

1 Answers1

0

If your principal is a custom type you will need to add a reflection hint so that it can be used in a SpEL expression.

@TypeHint(types = CustomToken.class)

The default Spring Security types already have reflection hints as part of Spring Native.

  • Thank you for looking into my issue :D. I got it working without the TypeHint but I don't know exctly how (that was during some pom cleanup when I moved from spring-boot being referenced in dependenciesManagement to being parent pom). Maybe the security config explicitely referencing the CustomToken makes the TypeHint optional? – ch4mp Jan 25 '22 at 17:44
  • I'm glad you figured it out @ch4mp! It could be that Spring Native added the reflection hint for the custom class. It's hard to say for sure without seeing the exact sample. – Eleftheria Stein-Kousathana Jan 26 '22 at 08:51
  • The [project is public](https://github.com/ch4mpy/starter/blob/master/api/webmvc/proxies-api/src/main/java/com/c4_soft/starter/proxies/ProxiesApiApplication.java). I think the class is not flushed by AoT compiler [because if this](https://github.com/ch4mpy/starter/blob/65aeabd2ed59ccedf1bc6b044b91fcd784241453/api/webmvc/proxies-api/src/main/java/com/c4_soft/starter/proxies/security/ServletSecurityBeansOverrides.java#L24) – ch4mp Jan 26 '22 at 16:51