构造函数SimpleGrantedAuthority(Set <role>)未定义,这是错误

时间:2019-02-13 14:34:57

标签: java maven spring-boot

编码时出现错误,任何人都可以解决此错误 它的显示更改为将getRoles()返回为字符串,但我将其更改为字符串,但是如果我更改用户,仍然会出现错误

package com.deevia.otpGenaration.otpGenaration.service;

import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.deevia.otpGenaration.otpGenaration.model.User;
import  com.deevia.otpGenaration.otpGenaration.repositories.UserRepository;

@Service
public class MyUserDetailsService {
    @Autowired
    private UserRepository userRepository;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        GrantedAuthority authority = new SimpleGrantedAuthority(user.getRoles());
        UserDetails userDetails = (UserDetails) new org.springframework.security.core.userdetails.User(user.getUsername(),
        user.getPassword(), Arrays.asList(authority));

        return userDetails;
    }
}

1 个答案:

答案 0 :(得分:0)

通常会出现该错误,因为SimpleGrantedAuthority构造函数正在接受StringSimpleGrantedAuthority(java.lang.String role)

我不知道getRoles()类中com.deevia.otpGenaration.otpGenaration.model.User的返回类型是什么,但是 如果它是字符串的集合,则可以使用流进行映射 user.getRoles().stream().map(SimpleGrantedAuthority::new).collect(java.util.stream.Collectors.toList());并将其传递给UserDetails