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 Object[] getMyComplaints(Authentication authentication)
{
String username = authentication.getName();
//System.out.println(username);
String user_type = "student";
List 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?
解决方案
Zuul by default does not forwards your Authorization header . You will have to explicitly configure in zuul to make it do this.
Your services must be on different server.
You have to change sensitve header settings in zuul properties (may be application.yml). By default it takes the following input.
zuul:
routes:
users:
path: /myusers/**
sensitiveHeaders: Cookie,Set-Cookie,Authorization
url: https://downstream
If you are very sure to forward your header in all services then only change this to
zuul:
routes:
users:
path: /myusers/**
sensitiveHeaders:
url: https://downstream
I hope this helps.