【问题标题】:Where do the Spring Security Authentication and Principal objects come from in a controller's methods?Spring Security Authentication 和 Principal 对象在控制器的方法中来自哪里?
【发布时间】:2021-10-05 15:10:23
【问题描述】:

我在 Spring Boot @RestController 中有一些方法,当我将它们添加为参数时,它们神奇地似乎可以访问 Spring Security AuthenticationPrincipal 对象。我想知道,我的方法如何处理这些参数?他们来自哪里? 这是一个例子:

@GetMapping("/someEndpoint")
public ObjectNode someEndpoint(Authentication authentication) {
    ...
    CustomAuthentication customAuthentication = (CustomAuthentication) authentication;
    logger.debug("Name: {}", customAuthentication.getName());
    ...
}

@GetMapping("/anotherEndpoint)
public ObjectNode anotherEndpoint(Principal principal) {

    logger.debug(principal.getName());
    ...
}

不仅仅是AuthenticationPrincipal 对象。我有时在这些控制器端点中也看到了HttpServletRequest 和其他参数。它们来自哪里,为什么它们是可选的?我可以在我的方法中获取这些对象的列表吗?

【问题讨论】:

标签: spring-boot spring-mvc spring-security


【解决方案1】:

Spring 参考文档

中提供了您所有问题的答案

对于Authentication 相关问题,请通读以从高层次上了解它是如何在会话中提供的。继续阅读AbstractAuthenticationProcessingFilter

阅读文档以获取支持的控制器方法参数列表here

【讨论】:

  • 您在文档中是否有任何特定位置可以查看有关如何注入参数的信息?在过去的一周里,我已经多次阅读 MVC 和 Security 文档,但没有找到。这个答案的链接stackoverflow.com/a/29410196/1191849 非常详细地解释了它,我只是无法在文档中找到类似的东西。
  • (我正在寻找一个较低级别的“如何”,我真的被所有的Spring“魔法”吓坏了,想知道到底发生了什么)
  • 您的问题可能没有提及您所做的研究或您正在寻找的代码参考。我的回答是针对问题主题的,并且还提供了您正在寻找的列表。我了解您发现我的回答没有用,但希望表明我的回答没有错。
猜你喜欢
  • 2013-05-03
  • 2013-07-18
  • 2017-11-21
  • 2012-07-15
  • 2020-12-04
  • 1970-01-01
  • 2017-06-28
  • 2012-03-07
  • 1970-01-01
相关资源
最近更新 更多