Java Spring Security如何将主体注入控制器?
我可以获得如下代码所示的用户主体,但我对Spring Security如何知道注入正确的主体感到困惑。通常,我们会传递参数来调用带有参数的方法。那么,Spring在哪里使用主体args调用控制器方法呢?谢谢你的帮助Java Spring Security如何将主体注入控制器?,java,spring,spring-mvc,spring-security,Java,Spring,Spring Mvc,Spring Security,我可以获得如下代码所示的用户主体,但我对Spring Security如何知道注入正确的主体感到困惑。通常,我们会传递参数来调用带有参数的方法。那么,Spring在哪里使用主体args调用控制器方法呢?谢谢你的帮助 @ResponseBody @RequestMapping({"/api/user"}) public Principal user(Principal principal) { return principal; } 正如评论所说,HandlerMethodArgumen
@ResponseBody
@RequestMapping({"/api/user"})
public Principal user(Principal principal) {
return principal;
}
正如评论所说,
HandlerMethodArgumentResolver
是一个策略接口,用于在给定请求的上下文中将方法参数解析为参数值。实际上,主参数将在ServletRequestMethodArgumentResolver
中解析。Talk很便宜,并显示源代码
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
Class<?> paramType = parameter.getParameterType();
// WebRequest / NativeWebRequest / ServletWebRequest
if (WebRequest.class.isAssignableFrom(paramType)) {
if (!paramType.isInstance(webRequest)) {
throw new IllegalStateException(
"Current request is not of type [" + paramType.getName() + "]: " + webRequest);
}
return webRequest;
}
// ServletRequest / HttpServletRequest / MultipartRequest / MultipartHttpServletRequest
if (ServletRequest.class.isAssignableFrom(paramType) || MultipartRequest.class.isAssignableFrom(paramType)) {
return resolveNativeRequest(webRequest, paramType);
}
// HttpServletRequest required for all further argument types
return resolveArgument(paramType, resolveNativeRequest(webRequest, HttpServletRequest.class));
}
您正在寻找的界面是
HandlerMethodArgumentResolver
;还要阅读SpringMVC文档,了解DispatcherServlet是如何工作的。您的解释与代码不匹配。获取主体是通过在不使用Spring Security的请求上调用getPrincipal
来完成的。注入/获取委托人与Spring Security完全无关。真的吗?我发现通过在源代码中调用SecurityContextHolder.getContext().getAuthentication()
来获取主体。哪一类是getPrincipal
方法?这是Spring Security通过与http servlet请求集成最终完成的工作。在web方法中使用主体与Spring安全性无关。它将只为http请求注入当前主体,该请求可以使用Spring安全性,也可以不使用Spring安全性。总而言之,你的答案确实令人困惑。
@Nullable
private Object resolveArgument(Class<?> paramType, HttpServletRequest request) throws IOException {
//omitted......
else if (Principal.class.isAssignableFrom(paramType)) {
Principal userPrincipal = request.getUserPrincipal();
if (userPrincipal != null && !paramType.isInstance(userPrincipal)) {
throw new IllegalStateException(
"Current user principal is not of type [" + paramType.getName() + "]: " + userPrincipal);
}
return userPrincipal;
}
//omitted......
}