spring-projects / spring-graphql

Spring Integration for GraphQL
https://spring.io/projects/spring-graphql
Apache License 2.0
1.53k stars 306 forks source link

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

Closed nictas closed 3 months ago

nictas commented 3 months ago

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:

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.

bclozel commented 3 months ago

The @AuthenticationPrincipal injects whatever comes out of Authentication#getPrincipal as explained in the reference documentation.

I've changed your sample to use this instead and it works as expected:

    @QueryMapping
    public String getCurrentUser(@AuthenticationPrincipal User userDetails) {
        if (userDetails != null) {
            return String.format("Authenticated user %s with class %s", userDetails.getUsername(), userDetails.getClass()
                    .getName());
        }
        return "No authenticated user";
    }

Let us know if this works for you.

nictas commented 3 months ago

Yes, that works! Thanks for the help! :)