Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot “我自己也搞不清楚”;[UserDetailsService返回null,这是一种违反接口约定的行为]";?_Spring Boot_Spring Security_Spring Data Jpa - Fatal编程技术网

Spring boot “我自己也搞不清楚”;[UserDetailsService返回null,这是一种违反接口约定的行为]";?

Spring boot “我自己也搞不清楚”;[UserDetailsService返回null,这是一种违反接口约定的行为]";?,spring-boot,spring-security,spring-data-jpa,Spring Boot,Spring Security,Spring Data Jpa,我是spring boot和spring security的新手,无法独自理解以下错误。 我的spring boot应用程序只包含两个URL,一个是任何人都可以访问的URL,也就是说,只有其名称密码保存在数据库中,另一个是只有管理员才能访问的URL(添加用户并在MySql数据库中滚动)。 但当我传递用户名和密码时,它会说:- org.springframework.security.authentication.InternalAuthenticationServiceException: Us

我是spring boot和spring security的新手,无法独自理解以下错误。 我的spring boot应用程序只包含两个URL,一个是任何人都可以访问的URL,也就是说,只有其名称密码保存在数据库中,另一个是只有管理员才能访问的URL(添加用户并在MySql数据库中滚动)。 但当我传递用户名和密码时,它会说:-

org.springframework.security.authentication.InternalAuthenticationServiceException: UserDetailsService returned null, which is an interface contract violation
我在下面发布所有必要的课程:-

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        User user= repository.findByname(name);
        CustomUserDetail userDetail=null;
        if(user!=null){
            CustomUserDetail userDetails=new CustomUserDetail();
            userDetails.setUser(user);
        }else{
            throw new UsernameNotFoundException("User not exist with name :" +name);
        }
            return null;
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BasicConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable();
        http
                .authorizeRequests()
                     .antMatchers("/user/").permitAll()
                     .and()
                .authorizeRequests()
                     .antMatchers("/MiniApi/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encodePWD()
    {
        return new BCryptPasswordEncoder();
    }
}
@RestController
@RequestMapping("/MiniApi")
public class Admincontroller
{
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @PreAuthorize("hasAnyRole('ADMIN')")
    @PostMapping("/admin/add")
    public String addUser(@RequestBody User user)
    {
        String pwd = user.getPassword();
        String encryptPwd = passwordEncoder.encode(pwd);
        user.setPassword(encryptPwd);
        userRepository.save(user);
        return "User added successfully...";
    }
}
public class AnyOne {

    @GetMapping("/anyone")
    public String Anyone()
    {
        return "processing......";
    }
}
CustomUserDetailService:-

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        User user= repository.findByname(name);
        CustomUserDetail userDetail=null;
        if(user!=null){
            CustomUserDetail userDetails=new CustomUserDetail();
            userDetails.setUser(user);
        }else{
            throw new UsernameNotFoundException("User not exist with name :" +name);
        }
            return null;
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BasicConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable();
        http
                .authorizeRequests()
                     .antMatchers("/user/").permitAll()
                     .and()
                .authorizeRequests()
                     .antMatchers("/MiniApi/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encodePWD()
    {
        return new BCryptPasswordEncoder();
    }
}
@RestController
@RequestMapping("/MiniApi")
public class Admincontroller
{
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @PreAuthorize("hasAnyRole('ADMIN')")
    @PostMapping("/admin/add")
    public String addUser(@RequestBody User user)
    {
        String pwd = user.getPassword();
        String encryptPwd = passwordEncoder.encode(pwd);
        user.setPassword(encryptPwd);
        userRepository.save(user);
        return "User added successfully...";
    }
}
public class AnyOne {

    @GetMapping("/anyone")
    public String Anyone()
    {
        return "processing......";
    }
}
CustomUserDetail

public class CustomUserDetail implements UserDetails {

    private User user;

    /*Getter and Setter*/

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    /*Overriden methods from userDetail*/

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return user.getRoles().stream().map(role -> new SimpleGrantedAuthority("Role_"+role))
                .collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
控制器类:- 我没有创建两个@Restcontroller类,只有一个@RequestMapping()充当基本URL

管理员控制器:-

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        User user= repository.findByname(name);
        CustomUserDetail userDetail=null;
        if(user!=null){
            CustomUserDetail userDetails=new CustomUserDetail();
            userDetails.setUser(user);
        }else{
            throw new UsernameNotFoundException("User not exist with name :" +name);
        }
            return null;
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BasicConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable();
        http
                .authorizeRequests()
                     .antMatchers("/user/").permitAll()
                     .and()
                .authorizeRequests()
                     .antMatchers("/MiniApi/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encodePWD()
    {
        return new BCryptPasswordEncoder();
    }
}
@RestController
@RequestMapping("/MiniApi")
public class Admincontroller
{
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @PreAuthorize("hasAnyRole('ADMIN')")
    @PostMapping("/admin/add")
    public String addUser(@RequestBody User user)
    {
        String pwd = user.getPassword();
        String encryptPwd = passwordEncoder.encode(pwd);
        user.setPassword(encryptPwd);
        userRepository.save(user);
        return "User added successfully...";
    }
}
public class AnyOne {

    @GetMapping("/anyone")
    public String Anyone()
    {
        return "processing......";
    }
}
任何人:-

@Service
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    private UserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        User user= repository.findByname(name);
        CustomUserDetail userDetail=null;
        if(user!=null){
            CustomUserDetail userDetails=new CustomUserDetail();
            userDetails.setUser(user);
        }else{
            throw new UsernameNotFoundException("User not exist with name :" +name);
        }
            return null;
    }
}
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BasicConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception
    {
        auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.csrf().disable();
        http
                .authorizeRequests()
                     .antMatchers("/user/").permitAll()
                     .and()
                .authorizeRequests()
                     .antMatchers("/MiniApi/**").hasAnyRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }

    @Bean
    public BCryptPasswordEncoder encodePWD()
    {
        return new BCryptPasswordEncoder();
    }
}
@RestController
@RequestMapping("/MiniApi")
public class Admincontroller
{
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @PreAuthorize("hasAnyRole('ADMIN')")
    @PostMapping("/admin/add")
    public String addUser(@RequestBody User user)
    {
        String pwd = user.getPassword();
        String encryptPwd = passwordEncoder.encode(pwd);
        user.setPassword(encryptPwd);
        userRepository.save(user);
        return "User added successfully...";
    }
}
public class AnyOne {

    @GetMapping("/anyone")
    public String Anyone()
    {
        return "processing......";
    }
}
更改我所做的:- 若我正在从CustomUserDetailService中删除return语句,那个么我得到的是return语句丢失错误,然后我添加了return userDetails; 它给了我:-

首先它问我用户名和密码,我提供了它,然后这个

HTTP状态403–禁止

  • 您返回的是null,而不是
    userDetails

很抱歉,如果我删除retrun null,我会尝试它,因为返回语句丢失。我在上一节更新了帖子,我提到了我所做的更改…我提到了我所做的更改…以及我得到的输出。。。