Spring Security:无法构造 org.springframework.security.core.userdetails.UserDetails 的实例

Posted

技术标签:

【中文标题】Spring Security:无法构造 org.springframework.security.core.userdetails.UserDetails 的实例【英文标题】:Spring Security:Can not construct instance of org.springframework.security.core.userdetails.UserDetails 【发布时间】:2016-07-10 03:27:39 【问题描述】:

我正在从用户创建一个 X-Auth-Token。但是,当我尝试从生成的令牌中检索用户时,它给了我一个异常

Warning:   StandardWrapperValve[com.security.util.AppConfig]: Servlet.service() for servlet com.security.util.AppConfig threw exception
java.lang.IllegalStateException: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.security.core.userdetails.UserDetails, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: java.io.ByteArrayInputStream@7e618679; line: 1, column: 1]
    at com.security.util.TokenHandler.fromJSON(TokenHandler.java:81)
    at com.security.util.TokenHandler.parseUserFromToken(TokenHandler.java:55)
    at com.security.util.TokenAuthenticationService.getAuthentication(TokenAuthenticationService.java:43)
    at com.security.util.StatelessAuthenticationFilter.doFilter(StatelessAuthenticationFilter.java:34)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.Abstractiostrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of org.springframework.security.core.userdetails.UserDetails, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
 at [Source: java.io.ByteArrayInputStream@7e618679; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
    at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:857)
    at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:139)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3562)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2648)
    at com.security.util.TokenHandler.fromJSON(TokenHandler.java:79)
    ... 42 more

对于我正在使用的令牌生成:

public String createTokenForUser(UserDetails user) 
        byte[] userBytes = toJSON(user);
        byte[] hash = createHmac(userBytes);
        final StringBuilder sb = new StringBuilder(170);
        sb.append(toBase64(userBytes));
        sb.append(SEPARATOR);
        sb.append(toBase64(hash));
        return sb.toString();
    

为了从我正在使用的令牌中检索用户:

public UserDetails parseUserFromToken(String token) 
        final String[] parts = token.split(SEPARATOR_SPLITTER);
        if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) 
            try 
                final byte[] userBytes = fromBase64(parts[0]);
                final byte[] hash = fromBase64(parts[1]);

                boolean validHash = Arrays.equals(createHmac(userBytes), hash);
                if (validHash) 
                   //NEXT LINE I GET AN EXCEPTION
                    final UserDetails user = fromJSON(userBytes);
                        return user;
                
             catch (IllegalArgumentException e) 
                //log tempering attempt here
            
        
        return null;
    

这些是上述代码中使用的其他实用方法:

  private UserDetails fromJSON(final byte[] userBytes) 
            try 
                return new ObjectMapper().readValue(new ByteArrayInputStream(userBytes), UserDetails.class);
             catch (IOException e) 
                throw new IllegalStateException(e);
            
        

        private byte[] toJSON(UserDetails user) 
            try 
                return new ObjectMapper().writeValueAsBytes(user);
             catch (JsonProcessingException e) 
                throw new IllegalStateException(e);
            
        

        private String toBase64(byte[] content) 
            return DatatypeConverter.printBase64Binary(content);
        

        private byte[] fromBase64(String content) 
            return DatatypeConverter.parseBase64Binary(content);
        

        // synchronized to guard internal hmac object
        private synchronized byte[] createHmac(byte[] content) 
            return hmac.doFinal(content);
        


EDIT # 1:

public class CustomUserDetails extends org.springframework.security.core.userdetails.User

    private User user;

    public CustomUserDetails(String username, String password, Collection<? extends GrantedAuthority> authorities) 
        super(username, password, authorities);
    

    public CustomUserDetails(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) 
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    


    public CustomUserDetails(User user, Collection<? extends GrantedAuthority> authorities) 
        super(user.getUsername(), user.getPassword(), authorities);
        this.user = user;
    

    public CustomUserDetails(User user, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) 
        super(user.getUsername(), user.getPassword(), enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.user = user;
    

    public User getUser() 
        return user;
    

并修改了我的 toJSON 和 fromJSON 方法

private UserDetails fromJSON(final byte[] userBytes) 
        try 
            return new ObjectMapper().readValue(new ByteArrayInputStream(userBytes), CustomUserDetails.class);
         catch (IOException e) 
            throw new IllegalStateException(e);
        
    

    private byte[] toJSON(UserDetails user) 
        try 

            return new ObjectMapper().writeValueAsBytes( new CustomUserDetails(
                                user.getUsername(),
                                     user.getPassword(),  user.getAuthorities()));
         catch (JsonProcessingException e) 
            throw new IllegalStateException(e);
        
    

Now the exception is a changed to : 
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class com.security.CustomUserDetails]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)

【问题讨论】:

【参考方案1】:

您可以编写自己的反序列化器。将 JsonDeserialize 注解放在相关字段上。

    public class LoginUser implements UserDetails 

    ....getters and setters...

        @JsonDeserialize(using = CustomAuthorityDeserializer.class)
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() 
            return this.mAuthorities;
        

为该字段创建反序列化程序。

public class CustomAuthorityDeserializer extends JsonDeserializer 

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException 
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode jsonNode = mapper.readTree(jp);
        List<GrantedAuthority> grantedAuthorities = new LinkedList<>();

        Iterator<JsonNode> elements = jsonNode.elements();
        while (elements.hasNext()) 
            JsonNode next = elements.next();
            JsonNode authority = next.get("authority");
            grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
        
        return grantedAuthorities;
    


【讨论】:

【参考方案2】:

UserDetails 是一个接口,这是您的错误的原因 ObjectMapper read() 方法试图实例化它并失败。提供UserDetails 的自定义实现作为ObjectMapper.read() 方法的参数,它应该可以工作。

【讨论】:

感谢您的及时回复,我已经为 UserDetails 添加了一个实现,还修改了我的两个方法。但是,现在又遇到了一个异常 您应该实现UserDetails 而不是User 并将其提供给ObjectMapper.readValue()。你能用新的错误更新问题吗? 我已经实现了用户详细信息。我已经在最后一行更新了异常。没有找到适合类型的构造函数。

以上是关于Spring Security:无法构造 org.springframework.security.core.userdetails.UserDetails 的实例的主要内容,如果未能解决你的问题,请参考以下文章

Spring OAuth2 java.util.LinkedHashMap 无法转换为 org.springframework.security.web.authentication.WebAuthe

无法在 Spring Security 3 中允许静态资源

Spring security 无法自动装配 UserDetailsS​​ervice

禁用 Spring Security 导致无法加载应用程序上下文

Spring 3.0 - 无法找到 XML 模式命名空间的 Spring NamespaceHandler [http://www.springframework.org/schema/securit

Spring 3.0 - 无法找到 XML 模式命名空间的 Spring NamespaceHandler [http://www.springframework.org/schema/securit