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

后端 未结 2 1703
你的背包
你的背包 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 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.

提交回复
热议问题