There is a simple web service with one endpoint "GET /hello"
.
It would be good to declaratively describe in the controller that a JWT is expected in order to extract from it some data about the authorized user making the request.
Exploring some open source projects on Github, I see that the @AuthenticationPrincipal
annotation is somehow involved in the process. However, none of the tutorials I've managed to find mention such a declarative approach - they mostly show how to create a JWT, not how to deal with one.
I will be grateful if you point out noteworthy examples that I missed.
Obviously the problem is trivial and related to the basic capabilities of Spring Security, but I can't put the puzzle togeher.
Please, help me to find a proper (natural) way to pass JWT into the controller and get data from it.
Could you share a working example with dependencies and a small test showing how to work with JWT in controller?
SpringBoot 2.4.0
import org.springframework. ??? .Jwt;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
@RestController
public class MyController {
@GetMapping("hello")
public Object getRequests(@AuthenticationPrincipal Jwt jwt) {
String name = getPropertyFromJwt(jwt, "name");
String id = getPropertyFromJwt(jwt, "id");
return Map.of("name", name, "id", id);
}
}