package com.example.resourceserver.security; import java.util.Optional; import java.util.Set; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * This controller is a special one. The getRoles() method is accessed by calls from API gateway * when someone logs in to the API gateway. * * The path is publicly accessible. To prevent access via API gateway by API gateway clients, a different * path is used (not start with /api). * * SecurityConfig.java has been configured to allow access without authentication. * * AuthRestController */ @RestController @RequestMapping("/security/open/users") public class AuthRestController { private UserService userService; public AuthRestController(UserService userService) { this.userService = userService; } @GetMapping("/{username}/roles") public ResponseEntity getRoles(@PathVariable String username) { Optional user = userService.findByUsername(username); if (user.isEmpty()) { return ResponseEntity.ok(new RolesResponse(Set.of())); } return ResponseEntity.ok(new RolesResponse(user.get().getRoles())); } }