【问题标题】:Need to configure Spring Security and Hibernate需要配置 Spring Security 和 Hibernate
【发布时间】:2015-10-08 12:58:14
【问题描述】:

我正在尝试在我的 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>

【问题讨论】:

  • 会发生什么?您可以在不提示密码的情况下访问您的页面吗?
  • @AssenKolov 提交登录表单后没有任何反应。
  • 所以你尝试访问 /profile/xxx 然后你会看到登录页面,你登录并提交然后......什么都没有?没有反应? 200个空白页? 401? 403?
  • @AssenKolov 是的,当我提交表单 (.../login) 时没有任何反应。
  • 你是直接去 /login 还是尝试访问受保护的页面?

标签: java spring hibernate spring-mvc spring-security


【解决方案1】:

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

您可以只保护您的默认登录页面,或其他一些成功后登录页面,并且永远不要直接执行 /login,然后 spring security 会以正确的方式自动处理它。

【讨论】:

  • 我有 /signin?error 来处理我的配置中的错误,但即使提供了错误的凭据,页面也不会重定向到 /singin?error。
  • 问题一定是你的注册页面。我尝试了 spring-genereted 登录页面,它只是工作:我复制/粘贴您的配置,然后 1)删除与 UserService 的行和 2)将 configure() 重写为:http.formLogin().defaultSuccessUrl("/profile/xxx ").and().logout().and().authorizeRequests().antMatchers("/resources/**", "/", "/index", "/aboutus").permitAll().antMatchers( "/profile/**").hasRole("USER") 它工作正常:我去 /login,成功登录后我被重定向到 /profile/xxx
  • 我用你提到的那个替换了 configure 方法的主体,但它还不起作用。通过“删除用户服务行”,您指的是哪一行?调用 UserService (auth.userDetailsS​​ervice) 对象的行已被注释。
  • 我不得不删除@Autowired userDetailsS​​ervice,因为我没有任何定义。 “它不起作用”是一个相当模糊的描述。
  • “它不起作用”我的意思是它仍然处于相同的状态。不成功的尝试没有错误,成功的尝试没有方向。由于它适用于您但不适用于我,请您提供您的完整代码,我将用我的代码替换它以确保我们在同一页面上。
猜你喜欢
  • 2012-01-23
  • 2020-08-06
  • 2012-08-22
  • 2018-01-31
  • 2015-07-25
  • 2014-04-06
  • 2014-07-25
  • 1970-01-01
  • 2023-04-08
相关资源
最近更新 更多