创建名称为“ securityConfig”的bean时出错:通过字段“ securityService”表示的不满意的依赖性

时间:2019-03-12 11:04:07

标签: spring spring-boot spring-security spring-data-jpa

  

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'的bean时出错:通过字段'securityService'表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“ securityService”的bean时出错:通过字段“ userRepository”表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.BeanCreationException:创建名称为'userRepository'的bean时出错:调用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]上找不到具有给定名称[username]的Attribute。

0 个答案:

没有答案