Reputation: 23
I am working with Spring MVC and Spring Security for rest controllers, also I am using JWT. In some cases, I need to get a username from the token to provide it as a function parameter.
Now I am solving this problem by setting username as a request attribute in the security filter. Can you advise me on a better way to do this?
Rest controller:
@GetMapping(path = "/user", produces = "application/json")
public String getUserFromToken(@RequestAttribute(name = "username") String username) throws JsonProcessingException {
List<Data> dataSet = userService.doSomeProcessing(username);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(dataSet);
}
Security filter:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
final String requestTokenHeader = request.getHeader("Authorization");
String username = null;
String jwtToken = null;
if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
jwtToken = requestTokenHeader.substring(7);
try {
username = jwtTokenUtil.getUsernameFromToken(jwtToken);
} catch (IllegalArgumentException e) {
System.out.println("Unable to get JWT Token");
} catch (ExpiredJwtException e) {
System.out.println("JWT Token has expired");
}
}
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userService.loadUserByUsername(username);
if (jwtTokenUtil.validateToken(jwtToken, userDetails)) {
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
usernamePasswordAuthenticationToken
.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
request.setAttribute("username", jwtTokenUtil.getUsernameFromToken(jwtToken));
}
}
chain.doFilter(request, response);
}
Upvotes: 2
Views: 2012
Reputation: 26
You should read about principal https://www.baeldung.com/get-user-in-spring-security
There you will find a solution to this Spring Security problem, you yourself met with a similar one, thanks for the question and good luck
Upvotes: 1