spring-framework: Spring Boot 2.4 upgrade breaks injection of Principal

Affects: 2.4.0

Our code:

  fun me(@ApiIgnore principal: Principal): UserDetail {

used to inject the principal in Spring Boot versions prior to 2.4.0. Under 2.4.0 the argument is then null and our application breaks.

If the @ApiIgnore annotation is removed then the principal is then injected, however we don’t want the principal to be exposed in our API documentation since it is an internal parameter.

It appears that the bug was introduced in https://github.com/spring-projects/spring-framework/pull/25780. That PR doesn’t check to see if there is a AuthenticationPrincipal annotation on the field, merely that the parameter has any annotations at all so even Nonnull will break the injection.

We’ve tried adding the AuthenticationPrincipal annotation on the field, however that doesn’t work since the parameter resolver tries to inject authentication.getPrincipal which in our case is a String since we’re using spring security oauth2. We want the Principal injected instead.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 7
  • Comments: 23 (9 by maintainers)

Commits related to this issue

Most upvoted comments

so you are not supposed to use @AuthenticationPrincipal ?

No, it’s not that you are not supposed but that it doesn’t provide what you are trying to get. Your argument is Authentication but as per the Javadoc the annotation provides access to Authentication#getPrincipal(). The former is Principal, the latter is not.

@rstoyanchev I see your point, that the fix does indeed add the resolver. Nevertheless, I can confirm that I also suffer this problem under Spring Boot 2.4.1, and I have confirmed that the fix is visible in the code.

When I add the following (Java version of @electrified’s fix), then the problem disappears.

@Configuration
public class Something implements WebMvcConfigurer {

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
            resolvers.add(new PrincipalMethodArgumentResolver());
    }
}

Is the order of the resolvers relevant? I debugged a bit and with the @Configuration fix, the PrincipalMethodArgumentResolver is now added twice, the @Configuration class causes it to be added in spot 25 in the list for my example, along with being added to spot 33 by the RequestMappingHandlerAdapter.

In addition to the above change, the wiki has also been updated.

@michaelbrewer sounds like a duplicate of #26380.

Attempted upgrade from boot 2.3.4 to 2.4.1 and @AuthenticationPrincipal is now null in our relatively large application as well. Will try to debug a bit.

Our issue is fixed in Spring 2.4.1. We’ve removed @electrified fix and the application still works as expected 😁