Skip to content

@AuthenticationPrincipal injection in method parameters doesn't work #1039

@nictas

Description

@nictas

Hi,

I'm trying the inject the principal into the methods of my GraphQL @Controller class but I can't seem to get it working. I've created a small project that you can use to reproduce the problem (attached below). It consists of two classes:

  • SecurityConfig:
    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
    
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            return http.authorizeHttpRequests(customizer -> customizer.anyRequest()
                    .authenticated())
                    .httpBasic(Customizer.withDefaults())
                    .csrf(AbstractHttpConfigurer::disable)
                    .build();
        }
    
    }
  • GraphQLController
    @Controller
    public class GraphQLController {
    
        @QueryMapping
        public String getCurrentUser(@AuthenticationPrincipal Authentication principal) {
            if (principal != null) {
                return String.format("Authenticated user %s with class %s", principal.getName(), principal.getClass()
                        .getName());
            }
            principal = SecurityContextHolder.getContext()
                    .getAuthentication();
            if (principal != null) {
                return String.format("Authenticated user from SecurityContextHolder %s with class %s", principal.getName(),
                        principal.getClass()
                                .getName());
            }
            return "No authenticated user";
        }
    
    }

Project: graphql-demo.zip

You can use basic authentication with "user" as the username and the password from the application logs. Here's the GraphQL query:

query test {
	getCurrentUser
}

I always get the following response, which indicates that the injected @AuthenticationPrincipal is null and the one I get from SecurityContextHolder isn't:

{
	"data": {
		"getCurrentUser": "Authenticated user from SecurityContextHolder user with class org.springframework.security.authentication.UsernamePasswordAuthenticationToken"
	}
}

I'm using version 3.3.2 of the spring-boot-starter-graphql library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    for: stackoverflowA question that's better suited to stackoverflowstatus: invalidAn issue that we don't feel is valid

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions