Создание базового проекта Spring Security для учебных целей с использованием следующих зависимостей
web, lombock, validation, h2, jpa, oauth2, Configuration-processor.
При запуске проекта я получаю следующую ошибку в консоли.
Ошибка создания bean-компонента с именем
'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': не удалось внедрить автоматически подключенные зависимости
Ниже приведен необходимый код для контроллера и других необходимых файлов.
Контроллер
package controller;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.net.openssl.ciphers.Authentication;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class DashboardController {
@PreAuthorize("hasAnyRole('ROLE_MANAGER','ROLE_ADMIN','ROLE_USER')")
@GetMapping("/welcome-message")
public ResponseEntity getFirstWelcomeMessage(Authentication authentication){
return ResponseEntity.ok("Welcome to the JWT Tutorial:"+authentication.name()+"with scope:"+authentication.getClass());
}
@PreAuthorize("hasRole('ROLE_MANAGER')")
@GetMapping("/manager-message")
public ResponseEntity getManagerData(Principal principal){
return ResponseEntity.ok("Manager::"+principal.getName());
}
@PreAuthorize("hasRole('ROLE_ADMIN')")
@PostMapping("/admin-message")
public ResponseEntity getAdminData(@RequestParam("message") String message, Principal principal){
return ResponseEntity.ok("Admin::"+principal.getName()+" has this message:"+message);
}
}
Файл конфигурации безопасности
package config;
import config.userConfig.UserInfoManagerConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final UserInfoManagerConfig userInfoManagerConfig;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated();
// Disable CSRF (Cross-Site Request Forgery) for H2 console
http.csrf().ignoringAntMatchers("/h2-console/**");
// Allow framing of H2 console
http.headers().frameOptions().sameOrigin();
}
@Order(1)
@Bean
public SecurityFilterChain apiSecurityFilterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.requestMatcher(new AntPathRequestMatcher("/api/**"))
.csrf(AbstractHttpConfigurer::disable)
.authorizeRequests(auth -> auth.anyRequest().authenticated())
.userDetailsService(userInfoManagerConfig)
.formLogin(withDefaults())
.httpBasic(withDefaults());
return httpSecurity.build();
}
@Order(2)
@Bean
public SecurityFilterChain h2ConsoleSecurityFilterChainConfig(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.requestMatchers()
.antMatchers("/h2-console/**")
.and()
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.and()
.csrf()
.ignoringAntMatchers("/h2-console/**")
.and()
.headers()
.frameOptions().disable();
return httpSecurity.build();
}
}
Application.yml
spring:
h2:
console:
enabled: true
datasource:
url: jdbc:h2:mem:atquilDB
username: sa
password: sa
driverClassName: org.h2.Driver
jpa:
spring.jpa.database-platform: org.hibernate.dialect.H2Dialect
show-sql: true
hibernate:
ddl-auto: create-drop
logging:
level:
org.springframework.security: trace
Я использую JPA для взаимодействия с базой данных H2, вот подробности класса Repo
package repo;
import entity.UserInfoEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserInfoRepo extends JpaRepository {
Optional findByEmailId(String emailId);
}
Подробнее здесь: https://stackoverflow.com/questions/782 ... otation-we
Ошибка создания bean-компонента с именем «org.springframework.security.config.annotation.web.configuration.WebSecurityCo ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение