org.springframework.security.core.userdetails.User cannot be cast to MyUser

后端 未结 2 1704
你的背包
你的背包 2021-01-13 16:05

This is a spring security question.

I want to be able to retrieve my custom User object object using

SecurityContextHolder.getContext().getAuthentic         


        
相关标签:
2条回答
  • 2021-01-13 16:33

    You've overriden wrong method, additionally override createUserDetails which creates final User object from these fetched via loadUsersByUsername:

    @Override
    protected UserDetails createUserDetails(final String username,
        final UserDetails userFromUserQuery,
        final List<GrantedAuthority> combinedAuthorities) {
      String returnUsername = userFromUserQuery.getUsername();
    
      if (!isUsernameBasedPrimaryKey()) {
        returnUsername = username;
      }
    
      final MyUser userToReturn = new MyUser(returnUsername,
          userFromUserQuery.getPassword(), userFromUserQuery.isEnabled(), true,
          true, true, combinedAuthorities);
      userToReturn.setId(((MyUser) userFromUserQuery).getId());
      return userToReturn;
    }
    

    userToReturn.setId(((MyUser) userFromUserQuery).getId()); will work if you used your code, or you can remove loadUsersByUsername and fetch id right inside createUserDetails which doc's says:

    Can be overridden to customize the creation of the final UserDetailsObject which is returned by the loadUserByUsername method.

    0 讨论(0)
  • 2021-01-13 16:34

    Answering my own question -

    The issue was not overriding loadUserByUsername(String username) from JdbcDaoImpl.

    Therefore JdbcDaoImpl's implementation of loadUserByUsername(String username) was being called, which though internally was first calling loadUsersByUsername(String username), was subsequently adding granted authorities to the MyUser object returned above and returning it as a org.springframework.security.core.userdetails.User object.

    0 讨论(0)
提交回复
热议问题