I'm getting displayed unnecessary parameters in my REST api endpoints that use @AuthenticationPrincipal

Viewed 166

I noticed that in some of my REST API endpoints, Swagger UI display unnecessary parameters like accountNonExpired, accountNonLocked and so on

unnecessery parameters

I realized that it is caused by @AuthenticationPrincipal CurrentUser currentUser in those methods' body:

    @PutMapping("/change-email")
public ResponseEntity<?> changeEmail(@AuthenticationPrincipal CurrentUser currentUser,
                                     @RequestBody @Valid ChangeEmailRequest changeEmailRequest, BindingResult result){
    if (result.hasErrors()) return generateResponseFromBindingResult(result);

    try {
        userService.changeEmail(currentUser.getUser(), changeEmailRequest);
        return generateOkResponse("Changed email");
    } catch (ValidationException e) {
        return e.generateErrorResponse();
    }
}

CurrentUser class:

import org.springframework.security.core.userdetails.User;
public class CurrentUser extends User {
    private final pl.makary.entity.User user;
    public CurrentUser(String username, String password,
                       Collection<? extends GrantedAuthority> authorities,
                       pl.makary.entity.User user) {
        super(username, password, authorities);
        this.user = user;
    }
    public com.project.entity.User getUser() {return user;}
}

I was able to deal with couple of those parameters by adding @ApiParam(hidden = true) above every field in user entity, but those form org.springframework.security.core.userdetails.User stayed. I can't add annotation there, so I'm looking for other way i can get rid of those params. I tried adding @ApiParam(hidden = true) before @AuthenticationPrincipal in method body, and everywhere else where i could, but it didnt work.

1 Answers

You may have already solved this problem, but I will answer as others may have the same problem.

In the process of registering the Docket to the bean add ignoredParameterTypes(AuthenticationPrincipal.class) then the related class is no longer exposed in the api document.

I refer to this github issue

Let me show you in code

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket swaggerApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .ignoredParameterTypes(AuthenticationPrincipal.class) // Add This
                .apiInfo(swaggerInfo()).select()
                .apis(RequestHandlerSelectors.basePackage("com.example.project.controller"))
                .paths(PathSelectors.any())
                .build()
                .useDefaultResponseMessages(true);
    }

    private ApiInfo swaggerInfo() {
        return new ApiInfoBuilder().title("title")
                .description("desc")
                .license("license").licenseUrl("https://www.google.com/")
                .version("0.0.1")
                .build();
    }
}
Related