如何访问 Spring Boot 控制器内的 java.security.Principal 属性?
我有一个 Angular 前端,它提示用户使用 Microsoft Azure Active Directory 登录。当用户访问我的 API 时,正确的标头会添加到请求中。
我的 API 是一个根据此保护的 Spring Boot Rest API (保护资源服务器/API)指南。
我的控制器具有以下使用 java.security.Principal 接口作为参数的方法。
@GetMapping("/test")
ResponseEntity<Object> test(Principal principal) {
return ResponseEntity.ok(principal);
}
当我设置断点时,我会看到我想要获取的属性,例如principal.attributes.unique_name,但我无法通过主体接口访问这些属性。关于如何实现这一目标有什么想法吗?
PS:我看过类似的问题(如何从 java.security.Principal 获取所有属性?),但他们的答案无法帮助我......
I have an Angular frontend which prompts the user to login using Microsoft Azure Active Directory. The correct headers are added to the request when the user accesses my API.
My API is a Spring Boot Rest API secured according to this (Protect a resource server/API) guide.
My controller has the following method using the java.security.Principal interface as a parameter.
@GetMapping("/test")
ResponseEntity<Object> test(Principal principal) {
return ResponseEntity.ok(principal);
}
When I set a breakpoint I see the attributes I want to get like principal.attributes.unique_name, but I am not able to access those attributes through the Principal interface. Any idea on how to achieve this?
PS: I've had a look at similar questions like this one (How to get all attributes from java.security.Principal?), but their answers were not able to help me...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如本 Baeldung 指南中所述,您可以访问通过 SecurityContextHolder 的主体。
将此对象转换为 AADOAuth2AuthenticatedPrincipal 可提供对原则属性的访问,如下所示。
另一种选择是通过使用
@AuthenticationPrincipal
注释直接在控制器参数中使用AADOAuth2AuthenticatedPrincipal
,如下面的注释中所述。As stated in this Baeldung guide you can get access to the principal via the SecurityContextHolder.
Casting this object to AADOAuth2AuthenticatedPrincipal provides access to the principle properties as follows.
Another option is to use the
AADOAuth2AuthenticatedPrincipal
directly in the controller parameters by using the@AuthenticationPrincipal
annotation as pointed out in the comments below.