Ошибка при создании bean-компонента с именем securityConfig: неудовлетворенная зависимость выражается через поле securityService - PullRequest
1 голос
/ 12 марта 2019

SecurityConfig

package com.book.entity.security.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private Environment env;

    @Autowired
    private SecurityService securityService;

    private BCryptPasswordEncoder passwordEncoder() {
        return SecurityUtility.passwordEncoder();
    }

    private static final String[] PUBLIC_MATCHERS = { "/css/**", "/js/**", "/image/**", "/", "/myAccount" };

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().
        /* antMatchers("/**"). */
                antMatchers(PUBLIC_MATCHERS).permitAll().anyRequest().authenticated();

        http.csrf().disable().cors().disable().formLogin().failureUrl("/login?error").defaultSuccessUrl("/")
                .loginPage("/login").permitAll().and().logout()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/?logout")
                .deleteCookies("remember-me").permitAll().and().rememberMe();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(securityService).passwordEncoder(passwordEncoder());
    }
}

SecurityUtility

package com.book.entity.security.impl;
import java.security.SecureRandom;
import java.util.Random;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SecurityUtility {
    private static final String SALT = "salt"; // Salt should be protected carefully

    @Bean
    public static BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12, new SecureRandom(SALT.getBytes()));
    }

    @Bean
    public static String randomPassword() {
        String SALTCHARS = "ABCEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();

        while (salt.length() < 18) {
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;
    }
}

UserRepository

package com.book.entity.security.impl;

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

import com.book.entity.User;

@Repository
public interface UserRepository extends JpaRepository<User, Long>{
    User findByUsername(String userName);
}

SecurityService

package com.book.entity.security.impl;

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.book.entity.User;

@Service
public class SecurityService implements UserDetailsService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(userName);

        if (null == user) {
            throw new UsernameNotFoundException("Username not found");
        }

        return user;
    }
}

Ошибка: org.springframework.beans.factory.UnsatisfiedDependencyException: Ошибка создания компонента с именем 'securityConfig': Неудовлетворенная зависимость, выраженная через поле 'securityService'; вложенное исключение: org.springframework.beans.factory.UnsatisfiedDependencyException: ошибка при создании bean-компонента с именем securityService: неудовлетворенная зависимость, выраженная через поле userRepository; вложенное исключение: org.springframework.beans.factory.BeanCreationException: ошибка создания бина с именем userRepository: сбой вызова метода init; вложенным исключением является java.lang.IllegalArgumentException: не удалось создать запрос для метода public abstract com.book.entity.User com.book.entity.security.impl.UserRepository.findByUsername (java.lang.String)! Не удалось найти атрибут с указанным именем [имя пользователя] в этом ManagedType [com.book.entity.User]

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...