this is my first time asking a question so if I do something wrong please let me know.
I have an endpoint that looks like this:
@PostMapping("/operation/finiquito")
public ResponseEntity<?> calculateFiniquito(@AuthenticationPrincipal UserEntity user,
@RequestBody FiniquitoRequest finiquito, HttpServletRequest request)
throws IOException {
return service.calculateFiniquitoAndCreateHistory(user, finiquito, request);
}
For some context, its an endpoint that calculates a "Finiquito" which is the name of the check that you get when you are fired but in Spanish.
The endpoint works perfectly, the way the Authentication Principal is obtained is by a filter that esentially gets the token from the request and then, if its valid, it will get the user Id from the payload and search for said user in the database which esentially represents the UserEntity there in the parameters.
I am also showing the filter just in case:
@Log
@Component
@RequiredArgsConstructor
public class JwtAuthorizationFilter extends OncePerRequestFilter {
private final JwtTokenProvider tokenProvider;
private final ServicioUsuarioUserDetails userDetailsService;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
String token = getJwtFromRequest(request);
if (StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
Long userId = tokenProvider.getUserIdFromJWT(token);
UserEntity user = (UserEntity) userDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user,user.getRoles(), user.getAuthorities());
authentication.setDetails(new WebAuthenticationDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
//Just a log in case it fails, it translates to "haven´t been able to stablish user //authentication".
log.info("No se ha podido establecer la autenticación de usuario en el contexto de seguridad");
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader(JwtTokenProvider.TOKEN_HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith(JwtTokenProvider.TOKEN_PREFIX)) {
return bearerToken.substring(JwtTokenProvider.TOKEN_PREFIX.length(), bearerToken.length());
}
return null;
}
}
I am using Springfox for Swagger, my configuration docket bean is as follows:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.operaciones.microservicio.Controller"))
.paths(PathSelectors.any())
.build();
}
My question is: Is there any way to make SwaggerUI not ask for the UserEntity but just for the Authorization Header with annotations or am I gonna have to rewrite this endpoint and potentially also the filter if I want Swagger UI to represent it accordingly?
I would rather avoid if possible having to rewrite my code because I think that doing it this way looks pretty clean but because im still a Junior I assumed that this might be very bad practises maybe?
Some additional notes: if there is anything very wrong with my code above or some suggestions I will also take them. I am a junior developer so any criticism that can help me code better is always welcome.
I have tried searching on stack overflow for a solution but most of the swagger stuff that I found has to do with ASP and the little that I found of java do not answer my question.
Okay, I managed to find an answer by asking the devil´s artifact. I will leave the answer here in hopes that it will help people that might have a similar problem to me. You want to make sure you put @ApiIgnore in whatever field you dont want to be shown (in this case UserEntity) and then for it to ask for the Authorization Header you declare @ApiImplicitParam with the proper value.
@PostMapping("/operation/finiquito")
@ApiImplicitParams({
@ApiImplicitParam(name = "Authorization", value = "Authorization Bearer token", required = true, dataType = "string", paramType = "header")
})
public ResponseEntity<?> calculateFiniquito(@ApiIgnore @AuthenticationPrincipal UserEntity user,
@RequestBody FiniquitoRequest finiquito, HttpServletRequest request)
throws IOException {
return service.calculateFiniquitoAndCreateHistory(user, finiquito, request);
}