首页 > 解决方案 > spring-security authenticates and creates principal but controller gets different invalid user instance

问题描述

I just upgraded from spring-security 5.0.x to 5.1.3 and on deploying in-container I discovered that my services are not getting the authenticated user principal from spring-security.

Instead it looks like spring-webmvc is instantiated another instance of my user principal, but without all the user and LDAP details provided by spring-security.

I found one message from Spring https://github.com/spring-projects/spring-security/issues/3771 that seems relevant but it says I need to migrate from the old AuthenticationPrincipalArgumentResolver to the new one, however I'm not explicitly using it anywhere.

import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.security.core.annotation.AuthenticationPrincipal;

@Controller
public class MyService {

    @RequestMapping(value = "endpoint1",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String myEndpoint(
        @AuthenticationPrincipal(errorOnInvalidType = true) CustomUser user) {

I even put errorOnInvalidType in there but to no avail.

I've also tried creating my custom AuthenticationPrincipal annotation as per the docs https://docs.spring.io/spring-security/site/docs/5.1.3.RELEASE/api/

It does look like AuthenticationPrincipalArgumentResolver isn't doing its job but from debugging I see neither the upgraded version nor the older deprecated version are called (both are in spring-security-web)

Instead, I see a lot of spring-webmvc classes in the stack when creating the unwanted empty principal, stuff like HandlerMethodArgumentResolverComposite, so it looks to me like I've accidentally removed a crucial part of the config - either an annotation or a jar or an implementation.

Can anyone point out my error?

标签: javaspring-bootspring-security

解决方案


AuthenticationPrincipal好吧,我发现了如何通过手动创建AuthenticationPrincipalArgumentResolverbean来强制 Spring 解决这个问题。

使用 EnableWebSecurity 时,AuthenticationPrincipal 的信用为空


推荐阅读