@AuthenticationPrincipal如何运作?

时间:2016-12-14 22:58:49

标签: java spring spring-mvc spring-security

我无法理解@AuthenticationPrincipal是如何运作的? 据我所知,要激活此注释,我们必须添加注释驱动到dispatcher-servlet

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <bean
            class="org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver" />
    </mvc:argument-resolvers>
</mvc:annotation-driven>

@AutheticationPrincipal获取有关已登录用户的信息。

@RequestMapping
public String getCart(@AuthenticationPrincipal User activeUser) {
    Customer customer = customerService.getCustomerByUsername(activeUser.getUsername());
    int cartId = customer.getCart().getCartId();

    return "redirect:/customer/cart/" + cartId;
}

2 个答案:

答案 0 :(得分:1)

AuthenticationPrincipalArgumentResolver负责使用Authentication.getPrincipal()注释解析@AuthenticationPrincipal

您可以看到逻辑in the source code of AuthenticationPrincipalArgumentResolver

答案 1 :(得分:0)

Spring Security将注册默认过滤器SecurityContextPersistenceFilter

SecurityContextPersistenceFilter用于获取并将SecurityContext设置为SecurityContextHolder(这有一个实现SecurityContextHolderStrategy的属性,如果你做了&ThreadLocal则为SecurityContext #39;设置一个特殊模式),它通常从Session得到SecurityContextHolder(或者在经过审核后,将其他过滤器中的上下文设置为SecurityContext),我们可以得到在通过这种方式处理请求的线程中,通过静态方法SecurityContext context = SecurityContextHolder.getContext()

SecurityContextPersistenceFilter

最后,在请求完成后,Context将从SecurityContextHolder清除CMake Error at CMakeLists.txt:42 (find_package): By not providing "FindITK.cmake" in CMAKE_MODULE_PATH this project has asked CMake to find a package configuration file provided by "ITK", but CMake did not find one. Could not find a package configuration file provided by "ITK" with any of the following names: ITKConfig.cmake itk-config.cmake Add the installation prefix of "ITK" to CMAKE_PREFIX_PATH or set "ITK_DIR" to a directory containing one of the above files. If "ITK" provides a separate development package or SDK, be sure it has been installed. ,例如,某些线程会被重用,这可能会导致一些问题。