java - 需要配置Spring Security和Hibernate

标签 java spring hibernate spring-mvc spring-security

我正在尝试在我的 Spring + Hibernate 应用程序上实现 Spring Security。正在关注this question ,我删除了 SpringMvcInitializerSpringSecurityInitializer 但即使使用内存配置我也无法登录。

我想通过 hibernate 访问用户,但由于我无法通过数据库访问它们,因此我在本示例中使用 inMemoryAuthentication。

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("user@yahoo.com")
                .password("password1").roles("USER");
        // auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/resources/**", "/", "/index", "/aboutus")
                .permitAll()
                .antMatchers("/profile/**")
                .hasRole("USER")
                .and()
                .formLogin().loginPage("/signin").failureUrl("/signin?error")
                .permitAll().and().logout().logoutUrl("/signout").permitAll();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.2.xsd">


    <context:annotation-config />
    <mvc:annotation-driven />
    <mvc:view-controller path="/index" />
    <mvc:view-controller path="/" view-name="index" />
    <mvc:view-controller path="/aboutus" />
    <mvc:view-controller path="/signin" />



    <mvc:resources mapping="resources/**" location="resources/" />
    <context:component-scan base-package="com.myproject" />


    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.tiles3.TilesViewResolver" />
    <bean id="tilesConfigurer"
        class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
    </bean>

    <!-- Hibernate Config -->

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:8889/MyProject" />
        <property name="username" value="daniel" />
        <property name="password" value="daniel" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        depends-on="dataSource">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.myproject.model" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.use_sql_comments">true</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">validate</prop>
            </props>
        </property>
    </bean>


    <bean
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- End Hibernate Config -->
</beans>

最佳答案

如果你直接进入登录页面,就像你说的那样,登录后spring会进入默认的成功页面,这是你没有配置的。本页Moving Spring Security To Java Config, where does authentication-success-handler-ref go?建议使用.defaultSuccessUrl("/xxx"),虽然我没有尝试过。

你可以只保护你的默认登陆页面,或者其他一些成功登录后的页面,而不是直接执行/login,那么 spring security 会以正确的方式自动处理它。

关于java - 需要配置Spring Security和Hibernate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31498958/

相关文章:

java - 在子类上创建矩阵

java - 将 Gradle 属性添加到 application.properties 资源

spring - SQLSTATE(08006), ErrorCode(17002) 使用 HikariCP JDBC 连接池时

oracle - Grails域:找不到ID获取

java - java 中 .equals() 方法的假设 - 比较对象的实例或对象的状态

java - getter 和 setter findbugs 可能会暴露内部表示

java - 跳过 Spring 占位符替换

java - JPA @Column 注释创建评论/描述

java - 使用 Hibernate 计算和存储预先计算的平均值

java - 带有单选按钮的 JFrame 布局