gpt4 book ai didi

java - 获取错误 "No converter found capable of converting from type java.lang.String to type org.springframework.security.core.GrantedAuthority"

转载 作者:行者123 更新时间:2023-11-30 11:03:41 29 4
gpt4 key购买 nike

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

No converter found capable of converting from type java.lang.String to type 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();
}

用户服务

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

授权提供者

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);
}

最佳答案

错误提示的转换器是一个 JPA AttributeConverter . GrantedAuthority不是 JPA 实体,因此您需要一种方法将其映射到数据库列。您有 2 个选择:

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

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

关于java - 获取错误 "No converter found capable of converting from type java.lang.String to type org.springframework.security.core.GrantedAuthority",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30264344/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com