Предоставленные полномочия текстовое представление требуется в Spring Security - PullRequest
0 голосов
/ 01 апреля 2020

У меня проблема с разрешениями на регистрацию в 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);
    }
}

SecurityConfig

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

UserSerice

@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.IllegalArgumentException: Предоставленное полномочие текстовое представление требуется в org.springframework.util.Assert.hasText (Утверждение. java: 284) ~ [spring-core-5.2.4.RELEASE.jar: 5.2.4.RELEASE] в org.springframework.security.core.authority.SimpleGrantedAuthority. (SimpleGrantedAuthority. java: 38 ) ~ [spring-security-core-5.2.2.RELEASE.jar: 5.2.2.RELEASE] по адресу com.xxx.xx.models.User.getAuthorities (Пользователь. java: 71) ~ [classes /: na ] в java .base / jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) ~ [na: na] в java .base / jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAcce ssorImpl. java: 62) ~ [na: na] в java .base / jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl. java: 43) ~ [na: na] в java. base / java .lang.reflect.Mehod.invoke (Метод. java: 566) ~ [na: na]

Ответы [ 3 ]

0 голосов
/ 01 апреля 2020

Это мой JSON, и я использую defult 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 required\n at [Source: (PushbackInputStream); line: 4, column: 18] (through reference chain: com.xxx`enter code here`.xxx.models.User[\"authorities\"])",
    "path": "/register"
}**
0 голосов
/ 01 апреля 2020

Полагаю, вам нужно создать объект пользователя, например

new org.springframework.security.core.userdetails.Usersername, passwordEncoder.encode user.getPass ()), grantAuthorityList);

эта работа со мной!

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


}
0 голосов
/ 01 апреля 2020

В вашем классе модели User убедитесь, что установлена ​​роль, чтобы ваш метод getAuthorities () работал.

Ошибка, которую вы получаете, намекает на то, что вы выполняете «новый 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();
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...