Spring Security中需要一个授权文本表示



我在Spring Security中的注册权限有问题
我无法注册的方法

我试图设置每个路径的访问权限,但这对没有帮助

控制器

@RestController
public class UserController {
private UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/register")
public Long register(@RequestBody User user){
return userService.register(user);
}
}

安全配置

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
private UserDetailsServiceImpl userDetailsService;
public SecurityConfig(UserDetailsServiceImpl userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().disable();
http.authorizeRequests().
antMatchers("/").permitAll()
.antMatchers("/register").permitAll();
}
}

用户系列

@Service
public class UserService {
private UserRepository userRepository;
private PasswordEncoder passwordEncoder;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
public Long register(User user){
user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepository.save(user);
return user.getId();
}
}

用户模型

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.*;
@Entity
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String userName;
private String lastName;
private String password;
private String role;       
public User() {
}
..get and set...
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> listRole = new ArrayList<GrantedAuthority>();
listRole.add(new SimpleGrantedAuthority(role));
return listRole;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return userName;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}

错误

java.lang.IollegalArgumentException:授予权限的文本需要在org.springframework.util.Assert.hasText(Assert.java:284(~[spring-core-5.2.4.RELEASE.jar:5.2.4.REASE]org.springframework.security.core.authority.SimpleGrantedAuthority。(SimpleGrantedAuthority.java:38(~[sspring-security-core-5..2.2.RELEASE.jar:5.2.2.RELEASE]com.xxx.xx.models.User.getAuthorities(User.java:71(~[classes/:na]java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native方法(~[na:na]java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62(在java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43(在java.base/java.lang.reflect.Method.ioke(Method.java:566(~[na:na]

在用户模型类中,确保设置了角色,以便getAuthorities((方法正常工作。

您得到的错误提示您正在使用"null"角色执行"新的SimpleGrantedAuthority"。

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> listRole = new ArrayList<GrantedAuthority>();
listRole.add(new SimpleGrantedAuthority(role)); // this is the problematic line!
return listRole;
}

如果您没有角色,那么只需返回一个空列表即可。

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}

这是我的JSON,我使用defolt ROLE。我试图返回一个空列表,但我有同样的错误

{
"accountNonExpired": true,
"accountNonLocked": true,
"authorities": [
{
"authority": "string"
}
],
"credentialsNonExpired": true,
"enabled": true,
"id": 0,
"lastName": "Piotr",
"name": "Piotr",
"password": "Piotr",
"role": "ROLE_ADMIN",
"username": "Piotr"
}

错误表单POSTMAN

**"timestamp": "2020-04-01T15:20:05.670+0000",
"status": 500,
"error": "Internal Server Error",
"message": "JSON conversion problem: A granted authority textual representation is required; nested exception is com.fasterxml.jackson.databind.JsonMappingException: A granted authority textual representation is requiredn at [Source: (PushbackInputStream); line: 4, column: 18] (through reference chain: com.xxx`enter code here`.xxx.models.User["authorities"])",
"path": "/register"
}**

我认为您必须创建类似的用户对象

new org.springframework.security.core.userdetails.Usersername,passwordEncoder.encode user.getPass(((,grantedAuthorityList(

这是我的作品!

@Service  
public class UserSecurityService implements UserDetailsService {
@Autowired
YourRepository yourRepository;

@Autowired
PasswordEncoder passwordEncoder;

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
User user = yourRepository.findUserByUser(username);
List<String> listRoles = new ArrayList<>();
//List<UserRoles> userRoles = user.getUserRoleList();
user.getUserRoleList().forEach(role->listRoles.add(role.getRole().getRole()));// get role from database - usa il tuo modo **
grantedAuthorityList = listRoles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

//*** important ****
return new org.springframework.security.core.userdetails.User(username,
passwordEncoder.encode(user.getPass()), grantedAuthorityList);

}

相关内容

  • 没有找到相关文章

最新更新