Создание базового проекта 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
Программисты JAVA общаются здесь
1712650368
Гость
Создание базового проекта 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);
}
Подробнее здесь: [url]https://stackoverflow.com/questions/78296980/error-creating-bean-with-name-org-springframework-security-config-annotation-we[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия