当前位置: 首页 > 知识库问答 >
问题:

Spring4安全性,MySQL,c3p0连接。登录在Spring5中工作,但在Spring4中不工作

公孙锋
2023-03-14

>

  • 此代码在Spring5中工作。但我的公司需要Spring 4。

    在Spring4中,login与InMemoryAuthentication一起工作很好。但是当我添加了jdbc逻辑(c3p0,MySQL依赖关系&add DataSource代码&jdbc连接,c3p0连接池.properties文件);服务器运行,登录页打开,但身份验证失败(用户名/密码不正确)。

    下面是包结构

      null

        // set up variable to hold the properties. One can use spring helper classes or use @Autowired
        @Autowired
        private Environment env; // will hold the data read from the properties file
    
        // set up a logger for diagnostics
        private Logger logger = Logger.getLogger(getClass().getName());
    
        // define a bean for ViewResolver
        @Bean
        public ViewResolver viewResolver() {
    
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setPrefix("/WEB-INF/view/");
            viewResolver.setSuffix(".jsp");
    
            return viewResolver;
        }
    
        // define a bean for our security datasource
        @Bean
        public DataSource securityDataSource() {
    
            // create a connection pool
            ComboPooledDataSource securityDatasource  
                    = new ComboPooledDataSource();
    
            // set the jdbc driver
            try {
                securityDatasource.setDriverClass(env.getProperty("jdbc.driver"));
            } catch (PropertyVetoException exc) {
                // I'm wrapping this exception as runtime exception. It's unchecked and throwing that,
                // so, at least the system knows if something goes wrong, or if there's a problem
                throw new RuntimeException(exc); 
            }
    
            // log the connection props
            // just for sanity's sake. if it's reading from properties file
            logger.info(">>> jdbc.url= " + env.getProperty("jdbc.url"));
            logger.info(">>> jdbc.user= " + env.getProperty("jdbc.user"));
            logger.info(">>> jdbc.password= " + env.getProperty("jdbc.password"));
    
            // set the database connection props
            securityDatasource.setJdbcUrl(env.getProperty("jdbc.url"));
            securityDatasource.setUser(env.getProperty("jdbc.user"));
            securityDatasource.setPassword(env.getProperty("jdbc.password"));
    
            // set the connection pool props
            securityDatasource.setInitialPoolSize(
                    getIntProperty("connection.pool.initialPoolSize"));
    
            securityDatasource.setMinPoolSize(
                    getIntProperty("connection.pool.minPoolSize"));
    
            securityDatasource.setMaxPoolSize(
                    getIntProperty("connection.pool.maxPoolSize"));
    
            securityDatasource.setMaxIdleTime(
                    getIntProperty("connection.pool.maxIdleTime"));
    
            return securityDatasource;
        }
    
        // need a helper method
        // read environment property and convert to int
        private int getIntProperty(String propName) {
    
            String propValue = env.getProperty(propName);
    
            // now convert to int
            int intPropValue = Integer.parseInt(propValue);
    
            return intPropValue;
        }
    
    }
    
    // add a reference to our security data source
    @Autowired
    private DataSource securityDataSource;
    
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    
        /*
          //inMemoryAuthentication deprecated in latest Spring
          auth.inMemoryAuthentication().withUser("john").password("111").roles(
         "EMPLOYEE");
         auth.inMemoryAuthentication().withUser("mary").password("111").roles(
          "EMPLOYEE", "MANAGER");
         auth.inMemoryAuthentication().withUser("susan").password("111").roles(
          "EMPLOYEE", "ADMIN");
         */
    
        // use jdbc aunthetication
        // tell Spring Security to use JDBC authentication with our data source
        auth.jdbcAuthentication().dataSource(securityDataSource);
    }
    
    /**
     * Configure security of web paths in application, login, logout etc
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // .anyRequest().authenticated() // any request to the app must be authenticated
                // (i.e. logging in)
                .antMatchers("/").hasRole("EMPLOYEE").antMatchers("/leaders/**").hasRole("MANAGER")
    
                 // show our custom form at the request mapping "/showMyLoginPage"
                .antMatchers("/systems/**").hasRole("ADMIN").and().formLogin().loginPage("/showLoginPage")
    
                .loginProcessingUrl("/authenticateTheUser") // Login form should POST data to this URL for processing
    
                // (check username & password)
                .usernameParameter("username") // don't add this in spring 5
                .passwordParameter("password") // don't add this in spring 5
    
                .permitAll() // Allow everyone to see login page. No need to be logged in.
                .and().logout().permitAll().and().exceptionHandling().accessDeniedPage("/access-denied");
    }
    

    公共类AppSpringMvsDispatcherServlerInitializer扩展了AbstractAnnotationConfigDispatcherServletInitializer{

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {AppConfig.class};
    }
    
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }
    
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
    

    }

    下面是SecurityWebApplicationInitializer

    http://maven.apache.org/xsd/maven-4.0.0.xsd“>4.0.0

    <groupId>com.nike.mycoolwebapp</groupId>
    <artifactId>mycoolwebapp</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>
    
    <name>mycoolwebapp</name>
    
    <properties>
        <springframework.version>4.1.6.RELEASE</springframework.version>
        <springsecurity.version>4.0.1.RELEASE</springsecurity.version>
    
        <c3po.version>0.9.5.2</c3po.version>
    
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
    
        <!-- Spring MVC support -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>
    
        <!-- Spring Security -->
        <!-- spring-security-web and spring-security-config -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${springsecurity.version}</version>
        </dependency>   
    
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${springsecurity.version}</version>
        </dependency>   
    
        <!-- Add Spring Security Taglibs support -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>${springsecurity.version}</version>
        </dependency>
    
        <!-- Add MySQL support -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>
    
        <!-- Add c3p0 support -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3po.version}</version>
        </dependency>
    
        <!-- Servlet, JSP and JSTL support -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
    
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <!-- to compensate for java 9+ not including jaxb -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.3.0</version>
        </dependency>
    
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    
    </dependencies>
    
    <!-- TO DO: Add support for Maven WAR Plugin -->
    <build>
        <finalName>mycoolwebapp</finalName>
    
        <pluginManagement>
            <plugins>
                <plugin>
                    <!-- Add Maven coordinates (GAV) for: maven-war-plugin -->
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</version>                    
                </plugin>                       
            </plugins>
        </pluginManagement>
    </build>
    

    这里是AppController

    @Controller公共类AppController{

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showHome() {
        return "home";
    }
    
    // add a request mapping for /leaders
    @RequestMapping(value = "/leaders", method = RequestMethod.GET)
    public String showLeader() {
        return "leaders";
    }
    
    // add a request mapping for /systems
    @RequestMapping(value = "/systems", method = RequestMethod.GET)
    public String showAdmin() {
        return "systems";
    }
    
    @RequestMapping(value = "/showLoginPage", method = RequestMethod.GET)
    public String showLoginPage() {
        return "fancy-login";
    }
    
    // add a request mapping for /access-denied
    @RequestMapping(value = "/access-denied", method = RequestMethod.GET)
    public String showAccessDenied() {
        return "access-denied";
    }
    

    下面是MySQL表

  • 共有1个答案

    浦思源
    2023-03-14
    • 从数据库中删除{noop}。{noop}或{bcrypt}在Spring 5中。
     类似资料:
    • 以下连接字符串在我的站点中工作正常: 但是,当我试图设置DSN(使用64位odbc管理)时,我会遇到以下错误: 请记住,我使用的帐户和密码与连接字符串中使用的相同(这是有效的)。这也很奇怪,因为错误发生在我单击“SQL Server应该如何验证登录ID的真实性?”中的“下一步”之后。佩奇。 null

    • 为什么这个声明在debian linux gnu(x86_64)的Distrib 10.1.29-MariaDB中不起作用,而在MySQL中起作用? 错误: 错误1064(42000):您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册,了解使用由“MyPassword”标识的mysql_native_密码的近用户“root”@“localhost”的正确语法; 谢谢

    • 我是android开发的新手。尝试在Android web View中整合FB和Google+登录。FB登录正常。但谷歌登录是不允许登录的。我参考了几个链接,但无法成功。 问题是在Gmail中提供用户名和密码后,我的网站无法登录 webview覆盖在另一个webview上 Google登录不工作的android webview应用程序 Google登录不工作的android webview应用程序

    • 我有一段非常简单的Java代码,在那里我尝试从Java连接到我的Oracle DB。 在Windows下一切正常,但当我尝试在Ubuntu上运行时,我得到了一个错误。 我读了很多书,也试过很多解决方法。这是我的代码: 当我运行它时,我收到一个错误: 连接失败Java.sql.sqlRecoverable异常:IO错误:网络适配器无法在oracle.jdbc.driver.T4CConnection

    • 我使用一个包在Flutter中,它可以在Android上正常工作,但是当在ios模拟器上运行我的项目时,我在控制台中收到错误。 当我运行时,我得到以下错误,由于内容长度,我删除了错误的一些重复部分。 我在上面的错误中找不到任何相关消息这是 这就是我与pusher的连接方式 但在我注释掉上述文件和<code>pusher_client:^2.0.0<code>中的<code>时。yaml然后运行<c

    • 我已经从4.0升级了Spring版本。从x到4.2.3(刚才是4.2.4),@RequestBody注释中的“required=false”属性突然无法按预期工作(在版本更改之前)。 HttpStatus 415的服务器响应-不支持的媒体类型。 控制器方法(每个Spring版本相同)。 实际上,这并不是问题,因为从客户端开始,避免发送null,例如,设置empty实例就足以修复它。但我想了解,这个