1

I am trying to implement Spring Security on my Spring + Hibernate application. Following this question, I removed SpringMvcInitializer and SpringSecurityInitializer but I am unable to login even with inmemory configuration.

I would like to access users through hibernate but as I cannot access them through database I am using inMemoryAuthentication for this example.

@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>
Community
  • 1
  • 1
Daniel Newtown
  • 2,873
  • 8
  • 30
  • 64

1 Answers1

0

If you go to the login page directly, as you say you do, after login spring will go to the default success page, which you have not configured. This page Moving Spring Security To Java Config, where does authentication-success-handler-ref go? suggest using .defaultSuccessUrl("/xxx"), though I have not tried it.

You could just protect your default landing page, or some other after-successful-login-page, and never go directly do /login, then spring security will handle it automatically the right way.

Community
  • 1
  • 1
Assen Kolov
  • 4,143
  • 2
  • 22
  • 32
  • I have /signin?error to handle errors in my configuration but even after providing wrong credentials the page does not get redirected to /singin?error. – Daniel Newtown Jul 19 '15 at 11:43
  • The problem must be your signup page. I tried the spring-genereted login page and it just works: I copy/pasted your configuration, then 1) removed the line with UserService and 2) rewrote configure() to: http.formLogin().defaultSuccessUrl("/profile/xxx").and().logout().and().authorizeRequests().antMatchers("/resources/**", "/", "/index", "/aboutus").permitAll().antMatchers("/profile/**").hasRole("USER") It works fine: I go to /login, and after succesfull login I am redirected to /profile/xxx – Assen Kolov Jul 20 '15 at 10:09
  • I replaced the body of configure method with the one you mentioned but it does not work yet. By 'removed line with UserService' which line are you referring to? the line that was calling object of UserService (auth.userDetailsService) is commented. – Daniel Newtown Jul 20 '15 at 11:42
  • I had to remove the @Autowired userDetailsService because I don't have any defined. 'It does not work' is quite a vague description. – Assen Kolov Jul 20 '15 at 12:00
  • By 'it does not work' I meant it is still in the same condition. No error for unsuccessful attempts and no direction for successful attempts. As it works for you but not me, would you please include your complete code, I will replace that with mine to make sure we are on the same page. – Daniel Newtown Jul 20 '15 at 22:02