ritu4
ritu4

Reputation: 21

error while running the spring boot program

Description

I have created a database with three tables

users (user_id, name, password), 

the Role table with columns

    role_id, role and the third column Role_user with user_id,role_id.

error while running the program,

I have stored the username, passwords with the help of hashing with SHA2, for security purposes.

While running the program it is throwing the error as mentioned above. How should I resolve this error?

  package com.techprimers.security.securitydbexample.model;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "user")
public class Users {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "user_id")
   private int id;
   @Column(name = "password")
   private String password;
   @Column(name = "name")
   private String name;

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
   @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
   private Set<Role> roles;

   public Users() {
   }

   public Users(Users users) {
       this.roles = users.getRoles();
       this.name = users.getName();
       this.id = users.getId();
       this.password = users.getPassword();
   }

   public int getId() {
       return id;
   }

   public void setId(int id) {
       this.id = id;
   }


   public String getPassword() {
       return password;
   }

   public void setPassword(String password) {
       this.password = password;
   }

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }



   public Set<Role> getRoles() {
       return roles;
   }

   public void setRoles(Set<Role> roles) {
       this.roles = roles;
   }
} 

Role

package com.MonitoringDashboardNew.Model;

import javax.persistence.*;

@Entity
@Table(name = "role")
public class Role {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   @Column(name = "role_id")
   private int roleId;

   @Column(name = "role")
   private String role;

   public Role() {
   }

   public int getRoleId() {
       return roleId;
   }

   public void setRoleId(int roleId) {
       this.roleId = roleId;
   }

   public String getRole() {
       return role;
   }

   public void setRole(String role) {
       this.role = role;
   }
}

CustomUserDetails


package com.MonitoringDashboardNew.Model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.stream.Collectors;

public class CustomUserDetails extends Users implements UserDetails {

    public CustomUserDetails(final Users users) {
        super(users);
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        return getRoles()
                .stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
                .collect(Collectors.toList());
    }

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

    @Override
    public String getUsername() {
        return super.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;
    }
} 

Repository


package com.MonitoringDashboardNew.Repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.MonitoringDashboardNew.Model.Users;

@Repository
public interface UsersRepository extends JpaRepository<Users, Integer> {
    Optional<Users> findByName(String username);

}

Service


package com.MonitoringDashboardNew.Services;


import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.MonitoringDashboardNew.Model.CustomUserDetails;
import com.MonitoringDashboardNew.Model.Users;
import com.MonitoringDashboardNew.Repository.UsersRepository;

import java.util.Optional;


@Service
public abstract class CustomUserDetailsService implements UserDetailsService {

   @Autowired
   private UsersRepository usersRepository;


   public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
       Optional<Users> optionalUsers = usersRepository.findByName(name);
      // Optional<Users> optionalUsers = usersRepository.findById(id);

       optionalUsers
               .orElseThrow(() -> new UsernameNotFoundException("Username not found"));
       return optionalUsers
               .map(CustomUserDetails::new).get();
   }
}

SecurityConfuguration



package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.MonitoringDashboardNew.Services.CustomUserDetailsService;

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@EnableJpaRepositories()
@Configuration
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    @Autowired
    private CustomUserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userDetailsService)
        .passwordEncoder(getPasswordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("**/monitoring/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .formLogin().permitAll();
    }


    private PasswordEncoder getPasswordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return true;
            }
        };
    }
}

Error

Description:

Field userDetailsService in com.example.demo.SecurityConfiguration required a bean of type 'com.MonitoringDashboardNew.Services.CustomUserDetailsService' that could not be found.

The injection point has the following annotations:

@org.springframework.beans.factory.annotation.Autowired(required=true)

Action:

Consider defining a bean of type 'com.MonitoringDashboardNew.Services.CustomUserDetailsService' in your configuration.



Upvotes: 0

Views: 33

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36113

Your CustomUserDetailsService is abstract and cannot be created.

@Service
public abstract class CustomUserDetailsService implements UserDetailsService {

Make it non abstract:

@Service
public class CustomUserDetailsService implements UserDetailsService {

Upvotes: 1

Related Questions