Ошибка при создании bean-компонента. С аутентификацией JWT - PullRequest
0 голосов
/ 17 июня 2020

Я новичок в Spring Boot. Я разрабатывал приложение basi c crud, используя Angular и Spring Boot. Учебник, который я использую, - https://www.javainuse.com/spring/ang7-jwt Все работало нормально, пока я не применил аутентификацию JWT. При запуске выдает ошибку, которую я не могу исправить.

MY STACKTRACE:

2020-06-17 19:30:03.203  INFO 10920 --- [           main] c.j.SpringBootHelloWorldApplication      
: Starting SpringBootHelloWorldApplication on DESKTOP-GIIJPHC with PID 10920 (started by Dell in 
E:\Spring Boot\angular-spring)
2020-06-17 19:30:03.213  INFO 10920 --- [           main] c.j.SpringBootHelloWorldApplication      : 
No active profile set, falling back to default profiles: default
2020-06-17 19:30:04.715  INFO 10920 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : 
Tomcat initialized with port(s): 8081 (http)
2020-06-17 19:30:04.747  INFO 10920 --- [           main] o.apache.catalina.core.StandardService   : 
Starting service [Tomcat]
2020-06-17 19:30:04.747  INFO 10920 --- [           main] org.apache.catalina.core.StandardEngine  : 
Starting Servlet Engine: Apache Tomcat/9.0.13
2020-06-17 19:30:04.779  INFO 10920 --- [           main] o.a.catalina.core.AprLifecycleListener   : 
The APR based Apache Tomcat Native library which allows optimal performance in production 
 environments was not found on the java.library.path: [C:\Program 
Files\Java\jre1.8.0_251\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program 
Files/Java/jre1.8.0_251/bin/server;C:/Program Files/Java/jre1.8.0_251/bin;C:/Program 
Files/Java/jre1.8.0_251/lib/amd64;C:\Program Files 

Initializing Spring embedded WebApplicationContext
2020-06-17 19:30:04.904  INFO 10920 --- [           main] o.s.web.context.ContextLoader            : 
Root WebApplicationContext: initialization completed in 1600 ms
2020-06-17 19:30:05.091  WARN 10920 --- [           main] ConfigServletWebServerApplicationContext : 
 Exception encountered during context initialization - cancelling refresh attempt: 
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': 
 Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: 
 @Order on WebSecurityConfigurers must be unique. Order of 100 was already used on 
 com.javainuse.SecurityConfig$$EnhancerBySpringCGLIB$$9bb43797@7e11ab3d, so it cannot be used on 
 com.javainuse.config.WebSecurityConfig$$EnhancerBySpringCGLIB$$155c835f@5fa47fea too.
 2020-06-17 19:30:05.093  INFO 10920 --- [           main] o.apache.catalina.core.StandardService   : 
 Stopping service [Tomcat]
 2020-06-17 19:30:05.104  INFO 10920 --- [           main] ConditionEvaluationReportLoggingListener : 



 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 
 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': 
 Injection of autowired dependencies failed; nested exception is java.lang.IllegalStateException: 
 @Order on WebSecurityConfigurers must be unique. Order of 100 was already used on 
 com.javainuse.SecurityConfig$$EnhancerBySpringCGLIB$$9bb43797@7e11ab3d, so it cannot be used on 
 com.javainuse.config.WebSecurityConfig$$EnhancerBySpringCGLIB$$155c835f@5fa47fea too.

Я нигде в своем файле не использовал аннотацию @Order. ТАК, я не знаю, почему это дает мне эти ошибки. МОЖЕТ ЛИ ПОМОЧЬ? Совместное использование некоторых моих файлов здесь: application.properties:

jwt.secret=javainuse
jwt.get.token.uri=/authenticate

spring.main.allow-bean-definition-overriding=true

SecurityConfig. java:

package com.javainuse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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;

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


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

            authorizeRequests().antMatchers(HttpMethod.OPTIONS, 
   "/**").permitAll().anyRequest().authenticated()
            .and().httpBasic();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("admin").password("{noop}admin").roles("USER");
}
}

WEbSecurityConfig. java:

// I have not mentioned the import statements//

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

@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

@Autowired
private UserDetailsService jwtUserDetailsService;

@Autowired
private JwtRequestFilter jwtRequestFilter;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    // configure AuthenticationManager so that it knows from where to load
    // user for matching credentials
    // Use BCryptPasswordEncoder
    auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    // We don't need CSRF for this example
    httpSecurity.csrf().disable()
            // dont authenticate this particular request
            . 
    authorizeRequests().antMatchers("/authenticate").permitAll().antMatchers(HttpMethod.OPTIONS, 
   "/**")
            .permitAll().
            // all other requests need to be authenticated
            anyRequest().authenticated().and().
            // make sure we use stateless session; session won't be used to
            // store user's state.


  exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    // Add a filter to validate the tokens with every request
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
 }
 }
...