I am developing a spring boot application having front end with angular6 and using Eureka for service registry and zuul for authentication gateway, both as separate service. I am using jwt for authentication.
When I hit the url localhost:8080/dis/academics/complaint/getMyComplaints with authorization header having value jwt token, then it goes to gateway service and then gateway forwards this to academics service after valid authentication at gateway.
Now I want to get username from token in academics service. How can I get it?
Controller in Gateway Service
@RestController
@RequestMapping("/dis")
public class AuthRestAPIs {
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginForm loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String jwt = jwtProvider.generateJwtToken(authentication);
//UserDetails userDetails = (UserDetails) authentication.getPrincipal();
UserPrinciple userPrincipal = (UserPrinciple) authentication.getPrincipal();
return ResponseEntity.ok(new JwtResponse(jwt, userPrincipal.getUsername(), userPrincipal.getUserType(), userPrincipal.getAuthorities()));
}
}
Controller in Academics Service
@RestController
@RequestMapping("/complaint")
public class ComplaintsController {
@RequestMapping(value = "/getMyComplaints", method = RequestMethod.GET)
public <T, U> Object[] getMyComplaints(Authentication authentication)
{
String username = authentication.getName();
//System.out.println(username);
String user_type = "student";
List<Object> complaints = new ArrayList<>();
if(user_type.equals("student"))
{
Collections.addAll(complaints, cleanlinessComplaintRepository.findByCreatedBy(username));
Collections.addAll(complaints, leComplaintRepository.findByCreatedBy(username));
Collections.addAll(complaints, facultyComplaintRepository.findByCreatedBy(username));
Collections.addAll(complaints, otherComplaintRepository.findByCreatedBy(username));
}
return complaints.toArray();
}
}
I have tried using Authentication class but getting null value. How can I achieve this?