Is there a way to transform a Spring Security Principal before it is injected in a RestController method?
Let's say I have defined the following class:
@RestController
public class MyController {
@GetMapping("/test")
public void getWithPrincipalA(@AuthenticationPrincipal PrincipalTypeA a) {
...
}
@GetMapping("/test")
public void getWithPrincipalB(@AuthenticationPrincipal PrincipalTypeB b) {
...
}
}
I know that these controller methods are ambiguous and I could do several things to solve that, but what I would rather do is transform the @AuthenticationPrincipal
to some type I can define myself. The result would become something like:
@RestController
public class MyController {
@GetMapping("/test")
public void getWithTransformedPrincipal(@AuthenticationPrincipal MyTransformedPrincipal principal) {
...
}
}
Now I basically could define a single controller for several different authentication principals, without having to change the API.
Any help would be appreciated :)
Too keep things simple and transparant you could simply transform the principal in your controller method and dispatch the generic principal from there.
@RestController
public class MyController {
@GetMapping("/test")
public void getWithTransformedPrincipal(@AuthenticationPrincipal Principal principal) {
GenericPrincipal generic = PrincipalTransformer.transform(principal);
doSomethingWithPrincipal(generic);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.