可以使用Spring Security访问Dao层

时间:2015-01-16 15:07:26

标签: hibernate spring-security

我尝试将Spring Security集成到我的webapp中。所以我实现了Spring Security提供的UserDetailsS​​ervice接口。我无法访问我的Dao图层。但是,当我测试它将是我的Junit时,Dao工作得很好。我需要一些建议,因为我已经尝试了所有我能想到的想法:

这是Spring Security Config:

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.2.xsd">


    <!-- -->
    <http auto-config="true"  use-expressions="true">
        <intercept-url pattern="/login" access="permitAll"/>
        <intercept-url pattern="/logout" access="permitAll"/>
        <intercept-url pattern="/register" access="permitAll"/>
        <intercept-url pattern="/dashboard/**" access="hasRole('ROLE_USER')" />
        <intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')" />

        <form-login login-page="/login" 
            authentication-failure-url="/login" 
            default-target-url="/dashboard"
            username-parameter="email"
            password-parameter="password"/>

        <access-denied-handler error-page="/login"/>

        <logout invalidate-session="true" 
            logout-success-url="/login" 
            logout-url="/j_spring_security_logout"
            delete-cookies="JSESSIONID"/>

        <session-management invalid-session-url="/login">
            <concurrency-control max-sessions="1" expired-url="/login"/>
        </session-management>

        <!-- 
        <remember-me token-validity-seconds="1209600"
                    remember-me-parameter="remember-me"/>
         -->            
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="loginManager" >
            <!-- <password-encoder hash="bcrypt" /> -->
            <password-encoder ref="encoder"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="encoder" 
            class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    <beans:constructor-arg name="strength" value="11" />
  </beans:bean>

</beans:beans>

这是我的Login.jsp:

<c:url var="loginUrl" value="j_spring_security_check"/>


<form method="post" action="${loginUrl}">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    <div>
        <input id="login-email" class="inp-txt" type="text" name="email" />
    </div>
    <div>
        <input id="login-pwd" class="inp-txt" type="password" name="password" />
    </div>
    <div>
        <input id="login-submit" class="submit-btn acc-btn" name="login" type="submit" value="Login" />
    </div>
    </form>

这是我的服务层:

@Override
public UserDetails loadUserByUsername(String email)
        throws UsernameNotFoundException {
    System.out.println("Login");
    Customer customer = customerDao.findCustomerByEmail(email);
    //System.out.println(customer.getEmail());
    System.out.println("Customer ");
    if(customer == null) {
        throw new UsernameNotFoundException("Could not find user " + email);
    }
    System.out.println("Customer is exisitn");
    System.out.println(customer.getId());
    User user = new User(
                        //CustomerContext.buildCustomerContext(customer.getId(), customer.getEmail()), 
                        customer.getEmail(),
                        customer.getPassword(), customer.getEnable(), true, true, true, 
                        getGrantedAuthorities(getRoles(customer.getRole())));
    return user;
}

/** @return list of roles
 * */
public List<String> getRoles(Role role) {
    List<String> roles = new ArrayList<String>();

    if( role == Role.ADMIN) {
        roles.add("ROLE_ADMIN");
    } else {
        roles.add("ROLE_MODERATOR");
        roles.add("ROLE_USER");
    }
    return roles;
}


/** @return assign authority to login customer. 
 * */
public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    for (String role : roles) {
        authorities.add(new SimpleGrantedAuthority(role));
    }
    return authorities;
}

这是我的Dao:

@Override
public Customer findCustomerByEmail(String email) {
    LOGGER.info("Find Customer By Email");
    Criteria cx = currentSession().createCriteria(Customer.class);
    LOGGER.info("Done Create Criteria");
    Customer customer  = (Customer)cx
            .add(Restrictions.eq(CustomerDataInfo.EMAIL, email))
            .add(Restrictions.eq(CustomerDataInfo.ROLE, Role.CUSTOMER))
            .uniqueResult()
            ;
    LOGGER.info("Found the Customer");
    return customer;
}

当我尝试使用Spring Security访问Dao层时,它不会显示字符串“Done Create Critera”(currentSession()只返回sessionFactory创建的会话)。我不知道为什么它会打到那条线,但是当我用这个方法和其他方法运行我的Junit时,一切都运行正常。

0 个答案:

没有答案