2016-03-24 26 views
0

JDK 1.8およびSpring Boot 1.2.0 RELEASEを使用しています。 Spring Securityチュートリアルを使用したエラービルドプロジェクト

私のpom.xmlファイル:

<?xml version="1.0" encoding="UTF-8"?> 
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://maven.apache.org/POM/4.0.0" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>com.sampleapp</groupId> 
    <artifactId>sampleapp</artifactId> 
    <version>1.0-SNAPSHOT</version> 
    <packaging>war</packaging> 

    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.2.0.RELEASE</version> 
    </parent> 

    <name>Spring Boot Security Example</name> 

    <properties> 
     <java.version>1.8</java.version> 
    </properties> 

    <dependencies> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-test</artifactId> 
      <scope>test</scope> 
      <exclusions> 
       <exclusion> 
        <groupId>org.springframework</groupId> 
        <artifactId>spring-test</artifactId> 
       </exclusion> 
      </exclusions> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-freemarker</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-security</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-jpa</artifactId> 
     </dependency> 

     <!-- HSQLDB --> 
     <dependency> 
      <groupId>org.hsqldb</groupId> 
      <artifactId>hsqldb</artifactId> 
     </dependency> 
    </dependencies> 
</project> 

私のメインのアプリ:

package com.sampleapp; 

import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.boot.builder.SpringApplicationBuilder; 
import org.springframework.boot.context.web.SpringBootServletInitializer; 

@SpringBootApplication 
public class Application extends SpringBootServletInitializer { 

    public static void main(String[] args) { 
     SpringApplication.run(Application.class, args); 
    } 

    @Override 
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
     return application.sources(Application.class); 
    } 
} 

マイSecurityConfigファイル:

package com.sampleapp.config; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.autoconfigure.security.SecurityProperties; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.core.annotation.Order; 
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.WebSecurityConfigurerAdapter; 
import org.springframework.security.core.userdetails.UserDetailsService; 
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 

@Configuration     
@EnableGlobalMethodSecurity(prePostEnabled = true) 
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) 
class SecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    private UserDetailsService userDetailsService; 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() 
      .antMatchers("/", "/public/**").permitAll() 
      .antMatchers("https://stackoverflow.com/users/**").hasAuthority("ADMIN") 
      .anyRequest().fullyAuthenticated() 
      .and() 
      .formLogin() 
      .loginPage("/login") 
      .failureUrl("/login?error") 
      .usernameParameter("email") 
      .permitAll() 
      .and() 
      .logout() 
      .logoutUrl("/logout") 
      .deleteCookies("remember-me") 
      .logoutSuccessUrl("/") 
      .permitAll() 
      .and() 
      .rememberMe(); 
    } 

    @Override 
    public void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); 
    } 
} 

私のサンプルアプリケーションが、私には他のクラスとインタフェースをありますこの投稿をできるだけ単純で直感的なものにしておきたい。

私が使用してこれを実行します。

MVNスプリングブートを:実行

は、次の例外を受け取る:私はおそらく間違って

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'securityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans. factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.sampleapp.config.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
    ... 52 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.security.core.userdetails.UserDetailsService com.sampleapp.config.SecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:558) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) 
    ... 74 more 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.core.userdetails.UserDetailsService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)} 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:530) 
    ... 76 more 
[INFO] ------------------------------------------------------------------------ 
[INFO] BUILD FAILURE 
[INFO] ------------------------------------------------------------------------ 
[INFO] Total time: 3.751 s 

何をしているのですか?彼のコードが動作

...私は変更さ唯一の事は、いくつかのパッケージ(名前空間)と一緒にsampleappするアプリの名前だった

http://kielczewski.eu/2014/12/spring-boot-security-application/

が、私はなぜだろう:私がこのコードをチェックアウト私はしていない?

EDITED(デビッド・ヘルナンデスの質問のために):

デイビッド、コメントへの感謝が、私は私はあなたの質問を理解していればSecurityConfigファイルがorg.springframework.security.core.userdetails.UserDetailsS​​erviceを使用しているのでわかりませんfrom Spring ...私がコピーしたコードには、SpringからUserDetailServiceを実装するCurrentUserDetailsS​​erviceがあります。これがあなたの質問だったら、コードは

package com.sampleapp.service.currentuser; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
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 com.sampleapp.domain.CurrentUser; 
import com.sampleapp.domain.User; 
import com.sampleapp.service.user.UserService; 

public class CurrentUserDetailsService implements UserDetailsService { 
    private static final Logger LOG = LoggerFactory.getLogger(CurrentUserDetailsService.class); 

    private final UserService userService; 

    @Autowired 
    public CurrentUserDetailsService(UserService userService) { 
     this.userService = userService; 
    } 

    @Override 
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { 
     LOG.debug("Authenticating user with email={}", email.replaceFirst("@.*", "@***")); 
     User user = userService.getUserByEmail(email) 
       .orElseThrow(() -> new UsernameNotFoundException(String.format("User with email=%s was not found", email))); 
     return new CurrentUser(user); 
    } 
} 

ハッピープログラミングです!あなたはパッケージをリファクタリング場合は、Application.javaがプロジェクト のルートにある デフォルトの春のブートを使用することによりその

com 
-sampleapp 
--other packages 
Application.java 

のようなものを持っている@ComponentScanし、スキャンする必要があることを確認する必要があり

+0

あなたは 'UserDetailsS​​ervice'実装を投稿できますか? 'Autowired'を通して正しく注入されていないという不満があります。 –

+0

David、ありがとうございます - あなたの質問に答えるために投稿を編集しました。 –

答えて

0

あなたはcom.sampleapp外の何かを持っている場合は、プロジェクトのルートに

@ComponeScanは、あなたがあなたのBAであなたの@ComponentScanを追加することができ、それ

を見ることができませんパッケージ

Ex。

@ComponentScan(basePackages = {"package containing UserDetailsService", "packages containing your app"}) 

私はそれがスキャンだと思うので、ComponentScanが

+0

Filippo - あなたの提案をありがとうが、それは私のコードを壊した。今はFileNotFoundExceptionを持っています。 @ComponentScanをどこに置くのですか? –

0

それが働いて手に入れた間違った場所にコンポーネントを見つけていない、あなたの場合は...私は私のサービスクラスの@Serviceがありませんでした。

関連する問題