I work on a CRUD API project using spring security framework and I want to implement authorization verification using JWT tokens.
Let's say I have 3 endpoints:
- Authentication controller where user can sign up or sign in if he has an account
- A dummy get that returns a string to make sure authorization works
- One where I can update information about the current user
My user would be like this
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String favoriteAnimal;
}
In my 3rd endpoint I would like to update the favorite animal of my user.
@PostMapping("/update")
public ResponseEntity<String> updatePet(@RequestBody UserDTO user) {
return new ResponseEntity<>(UserSevices.updateUserInfo, HttpStatus.OK);
}
What would be the correct way to make sure that the user calling this endpoint is the correct one with the JWT token?
I have my AuthorizationFilter
extending OncePerRequestFilter
and implementing doFilterInternal()
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
String token = getJWTFromRequest(request);
if(StringUtils.hasText(token) && tokenGenerator.validateToken(token)) {
String username = tokenGenerator.getUsernameFromJWT(token);
UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null,
userDetails.getAuthorities());
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
filterChain.doFilter(request, response);
}
We agree that when I will call the endpoint the user request will go through this filter? Is this filter correct?
Now in my service if I want to fetch the user by id how can I get the id?
I have to create a token with an ID key? The token is generate and given to the user when he first logs in.
I am sorry if it is a bit confusing but I have not been able to find information online.
I use the jjwt library for token