Пользовательская безопасность весенней загрузки не применяется - PullRequest
0 голосов
/ 09 мая 2020

Я делаю проект MVC с пружинной загрузкой и пружинной защитой и jsp. Я просто тренирую свою пружину, и у меня тот же проект работает без весенней загрузки. В настоящее время я перешел на springboot, и когда я его запускаю, пользовательская конфигурация безопасности никогда не применяется.

Я понятия не имею, что происходит.

application.properties

# JDBC properties
#
spring.datasource.url=jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC
spring.datasource.username=springstudent
spring.datasource.password=springstudent

# Spring Data JPA properties
spring.data.jpa.repository.packages=com.crm.dao
spring.data.jpa.entity.packages-to-scan=com.crm.beans

#
# SECURITY JDBC properties
#
security.datasource.jdbc-url=jdbc:mysql://localhost:3306/spring_security_demo_bcrypt?useSSL=false&serverTimezone=UTC
security.datasource.username=springstudent
security.datasource.password=springstudent
security.datasource.driver-class-name= com.mysql.jdbc.Driver

Конфигурация:

 @Configuration
    @EnableWebSecurity
    public class DemoSecurityConfig extends WebSecurityConfigurerAdapter {

        // add a reference to our security data source

        @Autowired
        @Qualifier("securityDataSource")
        private DataSource securityDataSource;


        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {

            auth.jdbcAuthentication().dataSource(securityDataSource);

        }

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers("/resources/**");
        }

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

            System.out.println("aplicando configuracion");
            http.authorizeRequests()
            .antMatchers("/employees/showForm*").hasAnyRole("MANAGER", "ADMIN")
            .antMatchers("/employees/save*").hasAnyRole("MANAGER", "ADMIN")
            .antMatchers("/employees/delete").hasRole("ADMIN")
            .antMatchers("/employees/**").hasRole("EMPLOYEE")
            .antMatchers("/resources/**").permitAll()
            .antMatchers("/showMyLoginPage").permitAll()
            .and()
            .formLogin()
                .loginPage("/showMyLoginPage")
                .loginProcessingUrl("/authenticateTheUser")
                .permitAll()
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/access-denied");

        }


    }

Конфигурация:

 @Configuration
@EnableJpaRepositories(basePackages={"${spring.data.jpa.repository.packages}"})
public class DemoDataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource appDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="spring.data.jpa.entity")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder, DataSource appDataSource) {
        return builder
                .dataSource(appDataSource)
                .build();
    }

    @Bean
    @ConfigurationProperties(prefix="security.datasource")
    public DataSource securityDataSource() {
        return DataSourceBuilder.create().build();
    }
}

POM. xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.crm</groupId>
    <artifactId>Crm-Pet-Clinic</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Crm-Pet-Clinic</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
    </properties>

    <dependencies>

            <!-- Add Spring Security Taglibs support -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
        </dependency>

        <!-- Servlet, JSP and JSTL support -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>


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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

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

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1 Ответ

0 голосов
/ 10 мая 2020

Кажется, проблема с файлом application.properties. Если у вас определено несколько источников данных, вам нужно использовать jdbc-url или jdbcUrl вместо url. Ниже приведен пример

# JDBC properties
# Change the below line to jdbc-url instead of url
spring.datasource.jdbc-url=jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC
# OR Change the below line to jdbcUrl instead of url
spring.datasource.jdbcUrl=jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC
spring.datasource.username=springstudent
spring.datasource.password=springstudent

Вместо url вам нужно указать его как jdbc-url или jdbcUrl. По умолчанию это именно то, что ищет Spring при создании bean-компонента DataSource. Прочтите здесь и здесь для получения дополнительной информации о том, как происходит привязка и как псевдонимы работают под капотом Spring. В этих же руководствах также есть информация о том, как поступать в подобных ситуациях, если вы предпочитаете не использовать go с конфигурациями пружины по умолчанию.

И, как примечание, с пружинной загрузкой. Вам не нужно указывать driver-class. Это определяется автоматически.

Spring Boot также предоставляет класс построителя служебных программ, называемый DataSourceBuilder, который можно использовать для создания одного из стандартных источников данных (если он находится в пути к классам). Строитель может определить тот, который нужно использовать, на основе того, что доступно в пути к классам. Он также автоматически определяет драйвер на основе URL-адреса JDB C.

...