Spring Security如何将主体注入控制器



我可以获得如下代码所示的用户主体,但我对Spring Security如何知道注入正确的主体感到困惑。通常,我们会传递args来调用带有参数的方法。那么,Spring在哪里用Principal参数调用Controller方法呢?谢谢你的帮助。

@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));
}

现在您可以看到键代码为Principal.class.isAssignableFrom(paramType(,如果您进一步查找,您可以看到代码SecurityContextHolder.getContext().getAuthentication()来获得实际参数。好的,仅此而已,感谢@chrylis对罢工的评论。

@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......
}

最新更新