Я разработал весеннее загрузочное приложение, включая весеннее средство безопасности
вот основной класс весеннего загрузочного приложения
@EnableJpaRepositories(basePackages="com.example.demoImmobilierBack.repository")
@SpringBootApplication(scanBasePackages = "com.example.demoImmobilierBack", exclude = {DataSourceAutoConfiguration.class })
public class DemoImmobilierBackApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(DemoImmobilierBackApplication.class, args);
}
@Bean
public CommonsRequestLoggingFilter requestLoggingFilter() {
CommonsRequestLoggingFilter loggingFilter = new CommonsRequestLoggingFilter();
loggingFilter.setIncludeClientInfo(true);
loggingFilter.setIncludeQueryString(true);
loggingFilter.setIncludePayload(true);
loggingFilter.setIncludeHeaders(false);
return loggingFilter;
}
@Bean(name="passwordEncoder")
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.HSQL).build();
}
@Bean
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("com.acme.domain");
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
// @Bean
// public EntityManagerFactory getEntityManagerFactory() {
// return
// }
/**
* CORS configuration
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:4200"
)
.allowedMethods(
"GET",
"PUT",
"POST",
"DELETE",
"PATCH",
"OPTIONS"
);
}
}
Вот весенняя конфигурация безопасности
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
public static final String CONNECTION_SUCCESSFULL = "Vous êtes connecté avec succès.";
public static final String BAD_CREDENTIAL = "L'email ou le mot de passe est invalide.";
public static final String AUTHENTICATION_REJECTED = "L'authentification est rejetée.";
private final MyUserDetailsService myUserDetailsService;
private final ObjectMapper objectMapper;
private final PasswordEncoder passwordEncoder;
// private final UserServiceImpl userServiceImpl;
@Autowired
public WebSecurityConfig(MyUserDetailsService userService, ObjectMapper objectMapper, PasswordEncoder passwordEncoder) {
this.myUserDetailsService = userService;
this.objectMapper = objectMapper;
this.passwordEncoder = passwordEncoder;
}
@Bean
public RequestBodyReaderAuthenticationFilter authenticationFilter() throws Exception {
RequestBodyReaderAuthenticationFilter authenticationFilter
= new RequestBodyReaderAuthenticationFilter();
authenticationFilter.setAuthenticationSuccessHandler(this::loginSuccessHandler);
authenticationFilter.setAuthenticationFailureHandler(this::loginFailureHandler);
authenticationFilter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/api/user/login", "POST"));
authenticationFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationFilter;
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(myUserDetailsService);
authProvider.setPasswordEncoder(passwordEncoder);
return authProvider;
}
@Bean("authenticationManager")
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.frameOptions().sameOrigin()
.and()
.authorizeRequests()
.antMatchers("/**/*.scss", "/**/*.js","/**/*.html").permitAll()
.antMatchers("/api/produitimmobilier/all").permitAll()
.antMatchers("/api/audit/dossier/*").permitAll()
.antMatchers("/api/user/createUser").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
// .and()
// .formLogin()
// .loginProcessingUrl("/api/user/login")
//the URL on which the clients should post the login information
// .usernameParameter("email")
//the username parameter in the queryString, default is 'username'
// .passwordParameter("password")
// //the password parameter in the queryString, default is 'password'
// .successHandler(this::loginSuccessHandler)
// .failureHandler(this::loginFailureHandler)
// .loginPage("/api/user/login")
// .defaultSuccessUrl("/").
// .failureUrl("/login?error")
// .failureUrl("/")
// .permitAll()
// .and()
// .logout()
// .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
// .logoutSuccessUrl("/")
// .logoutSuccessUrl("/login?logout")
.and()
.addFilterBefore(
authenticationFilter(),
UsernamePasswordAuthenticationFilter.class)
.logout()
.logoutUrl("/api/user/logout")
.logoutSuccessHandler(this::logoutSuccessHandler)
.invalidateHttpSession(true)
.deleteCookies("my-remember-me-cookie")
.permitAll()
.and()
.rememberMe()
//.key("my-secure-key")
.rememberMeCookieName("my-remember-me-cookie")
// .tokenRepository(persistentTokenRepository())
.tokenValiditySeconds(1 * 60)
// .tokenValiditySeconds(24 * 60 * 60)
.and()
.exceptionHandling()
.and()
.csrf().disable();
}
private void loginSuccessHandler(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
String email = (String)request.getAttribute("email");
UserDTO userDTO = myUserDetailsService.findByEmail(email);
UserDTO resultUserDTO = new UserDTO();
SecurityDTO securityDTO = userDTO.getSecurity();
securityDTO.setAuthenticated(true);
List<String> messages = (List<String>)(Object)Arrays.asList(WebSecurityConfig.CONNECTION_SUCCESSFULL);
resultUserDTO.setMessages(messages);
resultUserDTO.setSecurity(securityDTO);
response.setStatus(HttpStatus.OK.value());
objectMapper.writeValue(response.getWriter(), resultUserDTO);
}
private void loginFailureHandler(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException e) throws IOException {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
String message = "";
if (e instanceof BadCredentialsException) {
message = WebSecurityConfig.BAD_CREDENTIAL;
// objectMapper.writeValue(response.getWriter(), "L'email ou le mot de passe est invalide.");
} else {
message = WebSecurityConfig.AUTHENTICATION_REJECTED;
// objectMapper.writeValue(response.getWriter(), "L'authentification est rejetée.");
}
List<String> messages = (List<String>)(Object)Arrays.asList(message);
UserDTO result = new UserDTO();
result.setMessages(messages);
objectMapper.writeValue(response.getWriter(), result);
}
private void logoutSuccessHandler(
HttpServletRequest request,
HttpServletResponse response,
Authentication authentication) throws IOException {
response.setStatus(HttpStatus.OK.value());
objectMapper.writeValue(response.getWriter(), "Bye!");
}
Here is the userrepository class
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.email = :username or u.password = :password")
User findByEmailAndPassword(@Param("username") String email,
@Param("password") String password);
@Query("select u from User u where u.email = :email")
User findByEmail(@Param("email") String email);
@Query("select u from User u where u.email = :email")
public User findByLogin(String email);
<S extends User> S saveAndFlush(S entity);
void deleteInBatch(Iterable<User> entities);
<S extends User> S save(S entity);
Optional<User> findById(Long id);
boolean existsById(Long id);
List<User> findAll();
void deleteAll();
void deleteById(Long id);
void delete(User user);
long count();
}
Вот пользовательский репозиторий
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
@Query("select u from User u where u.email = :username or u.password = :password")
User findByEmailAndPassword(@Param("username") String email,
@Param("password") String password);
@Query("select u from User u where u.email = :email")
User findByEmail(@Param("email") String email);
@Query("select u from User u where u.email = :email")
public User findByLogin(String email);
<S extends User> S saveAndFlush(S entity);
void deleteInBatch(Iterable<User> entities);
<S extends User> S save(S entity);
Optional<User> findById(Long id);
boolean existsById(Long id);
List<User> findAll();
void deleteAll();
void deleteById(Long id);
void delete(User user);
long count();
}
Вот выдержка из пользовательского класса
@Getter
@Setter
@Table(name = "USER")
@Entity
public class User {
/**
* the ID of the product.
*/
@Id
@Column(name = "USER_ID")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
/**
* male (M) or Female (F).
*/
@Column(name = "GENDER")
private String gender;
/**
* last name.
*/
@Column(name = "LASTNAME")
private String lastName;
/**
* first name.
*/
@Column(name = "FIRSTNAME")
private String firstName;
/**
* email.
*/
@Column(name = "EMAIL")
Вот файл application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=@Marwen1
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyHbmImpl
spring.jpa.hibernate.naming.physical-strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
logging.level.org.springframework.web.filter.CommonsRequestLoggingFilter=DEBUG
spring.main.allow-bean-definition-overriding=true
вот дерево проекта
И вот исключение, которое я получил
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webSecurityConfig' defined in file [/Users/admin/GIT/demoImmobilierBack/target/classes/com/example/demoImmobilierBack/WebSecurityConfig.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailsService': Unsatisfied dependency expressed through field 'userServiceImpl'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.demoImmobilierBack.model.User
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Сед не рисус. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices диам. Maecenas ligula massa, varius a, semper congue, euismod non, mi. Proin porttitor, orci nec nonummy molestie, enim est eleifend mi, non fermentum diamnisl sit ameterat. Дуис семпер. Duis arcu massa, scelerisque vitae, consequat in, pretium a, enim. Пеллентеск Конго. Ut in risus volutpat libero pharetra tempor. Cras vestibulum bibendum augue. Praesent egestas leo in pede. Praesent blandit odio eu enim. Pellentesque Sed dui ut Augue blandit sodales. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Аликвам нибх. Mauris ac mauris sed pede pellentesque fermentum. Maecenas adipiscing ante non diam sodales hendrerit.
ПОДЕЛИТЬСЯ КОДОМ
@EnableJpaRepositories(basePackages="com.example.demoImmobilierBack.repository")
@SpringBootApplication(scanBasePackages = "com.example.demoImmobilierBack", exclude = {DataSourceAutoConfiguration.class })
@EntityScan(basePackages = "com.example.demoImmobilierBack.model")
public class DemoImmobilierBackApplication implements WebMvcConfigurer {
public static void main(String[] args) {
SpringApplication.run(DemoImmobilierBackApplication.class, args);
}
javax.persistence.Entity
- person gtiwari333   schedule 06.10.2020