blob: 0eb0d5167bc85b3dd49b2f43baf4eaf1e04f5055 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
package com.example.resourceserver.security;
import java.security.Principal;
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/security/users")
public class UserRestController {
private UserService userService;
public UserRestController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{username}/roles")
public ResponseEntity<RolesResponse> getRoles(@PathVariable String username) {
Optional<User> user = userService.findByUsername(username);
if (user.isEmpty()) {
return ResponseEntity.ok(new RolesResponse(Set.of()));
}
return ResponseEntity.ok(new RolesResponse(user.get().getRoles()));
}
@GetMapping("/test")
public String test(Principal principal) {
return principal.toString();
}
@GetMapping("/test-username")
public String testName(Principal principal) {
return principal.getName();
}
// Get roles using the Authentication object
@GetMapping("/test-roles-auth")
public Collection<String> getRoles(Authentication authentication) {
return authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
}
// Inspect raw JWT claims directly
@GetMapping("/test-roles-jwt")
public Map<String, Object> getClaims(@AuthenticationPrincipal Jwt jwt) {
return jwt.getClaims(); // Extract custom JSON fields containing roles
}
/* Not very secure because unverifiable headers can be introduced by unwanted parties */
@GetMapping("/test-roles-headers")
public String getRolesFromHeaders(@RequestHeader("X-User-Name") String username,
@RequestHeader("X-User-Roles") String roles) {
return "Roles: " + roles + ", username: " + username ;
}
}
|