得到错误"没有发现转换器能够从类型java.lang.String转换为类型org.springframework.security.core.GrantedAuthority"

时间:2015-05-15 16:23:46

标签: java spring spring-mvc spring-boot

我在我的应用程序中使用Spring Boot和Spring Security。当我从数据库中获取用户时,我收到以下错误,即使我包含了所有依赖项:

  

找不到能够从类型java.lang.String转换为org.springframework.security.core.GrantedAuthority

的转换器

这是如何引起的?如何解决?

我的实体是

public class User {
    public static final String USERNAME = "username";
    public static final String PASSWORD = "password";
    public static final String ROLES = "roles";

    @Id String id;

    String firstName;

     @JsonProperty(PASSWORD)
    String password;

    @JsonProperty(USERNAME)
    String userName;

    @JsonProperty(ROLES)
    @JsonSerialize(contentUsing = GrantedAuthoritySerializer.class)
    @JsonDeserialize(contentUsing = GrantedAuthorityDeserializer.class)
    private List<GrantedAuthority> roles;



    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

     public List<GrantedAuthority> getRoles() {
            System.out.println("roles"+roles);
            return roles;
        }

     @Override
        public String toString() {
            return new ToStringBuilder(this)
                    .append("username", userName)
                    .append("password", password)
                    .append("roles", roles)
                    .toString();
        }

UserService

User user = userRepository.findById("5555c3e77d6e5b11dd4ff858");

AuthProvider

UserDetails loadedUser;

        System.out.println("username"+username);

        try {
             com.samepinch.domain.user.User samepinchuser = userService.findUserByUsername(username);
            System.out.println("samepinchuser"+samepinchuser);
            loadedUser = new User(samepinchuser.getUserName(), samepinchuser.getPassword(),samepinchuser.getRoles());
            System.out.println("loaded user"+loadedUser);
        } catch (Exception repositoryProblem) {
            throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
        }

1 个答案:

答案 0 :(得分:1)

错误抱怨的转换器是JPA AttributeConverterGrantedAuthority不是JPA实体,因此您需要一种方法将其映射到数据库列。您有两个选择:

  1. 创建AttributeConverter,将GrantedAuthority转换为String(并根据界面返回)。 AttributeConverter需要包含在为JPA实体扫描的类中(将它放在与实体应该相同的包中)。

  2. 将权限建模为List<String>,然后提供一个只使用List<GrantedAuthority>转换为AuthorityUtils.createAuthorityList(String...)的get方法。