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

Java-Spring-由于未检测到事务而导致安全性不起作用

温举
2023-03-14

我试图建立一个简单的CRM spring应用程序与安全层。

我的用例很简单:登录页面,它允许访问客户列表,并从中添加新用户。

我已经为客户管理创建了一个客户端配置类和一个安全配置类。安全配置文件定义了自己的数据源、事务管理器和会话工厂,以访问管理用户的专用数据库:

@Configuration
@EnableWebSecurity
@PropertySource("classpath:security-persistence-mysql.properties")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    Environment env;
    private Logger logger = Logger.getLogger(getClass().getName());

    @Autowired
    private UserDetailsService userService;

    @Autowired
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Bean(name = "securitySessionFactory")
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(securityDataSource());
        sessionFactory.setHibernateProperties(hibernateProperties());
        sessionFactory.setPackagesToScan("com.luv2code.springdemo");

        return sessionFactory;
    }

    @Bean(name = "securityDataSource")
    public DataSource securityDataSource() {

        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(env.getProperty("jdbc.driver"));
        } catch (PropertyVetoException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        dataSource.setUser(env.getProperty("jdbc.user"));
        dataSource.setPassword(env.getProperty("jdbc.password"));
        dataSource.setJdbcUrl(env.getProperty("jdbc.security.url"));
        logger.info("URL security config : " + env.getProperty("jdbc.url"));

        dataSource.setInitialPoolSize(
                getPropertyAsInt("connection.pool.initialPoolSize"));
        dataSource.setMinPoolSize(
                getPropertyAsInt("connection.pool.minPoolSize"));
        dataSource.setMaxPoolSize(
                getPropertyAsInt("connection.pool.maxPoolSize"));
        dataSource.setMaxIdleTime(
                getPropertyAsInt("connection.pool.maxIdleTime"));

        return dataSource;
    }

    private int getPropertyAsInt(String key) {
        return Integer.parseInt(env.getProperty(key));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/customer/**").hasRole("EMPLOYE")
                .antMatchers("/leaders/**").hasRole("MANAGER")
                .antMatchers("/systems/**").hasRole("ADMIN")
                .antMatchers("/", "/home", "/createUser").permitAll()
                .anyRequest().authenticated().and().formLogin()
                .loginPage("/showMyLoginPage")
                .loginProcessingUrl("/authentificateTheUser")
                .successHandler(customAuthenticationSuccessHandler).permitAll()
                .and().logout().permitAll().and().exceptionHandling()
                .accessDeniedPage("/access-denied");

    }

    private Properties hibernateProperties() {

        Properties hibernatePpt = new Properties();
        hibernatePpt.setProperty("hibernate.dialect",
                env.getProperty("hibernate.dialect"));
        hibernatePpt.setProperty("hibernate.show_sql",
                env.getProperty("hibernate.show_sql"));
        hibernatePpt.setProperty("hibernate.packagesToScan",
                env.getProperty("hibernate.packagesToScan"));

        return hibernatePpt;
    }

    @Bean(name = "securtiyTransactionManager")
    @Autowired
    @Qualifier("securitySessionFactory")
    public HibernateTransactionManager transactionManager(
            SessionFactory sessionFactory) {

        // setup transaction manager based on session factory
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);

        return txManager;
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();

    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }

}
@Entity
@Table(name = "user")
public class User {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "username")
private String userName;

@Column(name = "password")
private String password;

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

@Column(name = "email")
private String email;

@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Collection<Role> roles;
//constructors, getter,setter

}
@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "name")
    private String name;

问题是使用事务性注释。首先,我通过控制器:

@Controller
public class LoginController {
    @GetMapping("/showMyLoginPage")
    public String showMyLoginPage() {
        return "login";
    }

    @GetMapping("/access-denied")
    public String showAccesDenied() {

        return "access-denied";
    }
}

然后jsp:

    <form:form method="GET" action="${pageContext.request.contextPath}/createUser">
    <input type="submit" value="Registration">
    </form:form>
public interface UserService extends UserDetailsService

@Service
@Transactional("securtiyTransactionManager")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Override
    public UserDetails loadUserByUsername(String userName)
            throws UsernameNotFoundException {
        User user = userDAO.getUser(userName);
        if (user == null) {
            throw new UsernameNotFoundException(
                    "Invalid username or password.");
        }
        return new org.springframework.security.core.userdetails.User(
                user.getUserName(), user.getPassword(),
                mapRolesToAuthorities(user.getRoles()));
    }




    private Collection<? extends GrantedAuthority> mapRolesToAuthorities(
            Collection<Role> roles) {
        return roles.stream()
                .map(role -> new SimpleGrantedAuthority(role.getName()))
                .collect(Collectors.toList());
    }
}

有关信息,完整的项目在这里:https://github.com/moutyque/crm

共有1个答案

曾嘉瑞
2023-03-14
    @Bean(name = "securtiyTransactionManager")
    @Autowired
    public HibernateTransactionManager transactionManager(
             @Qualifier("securitySessionFactory") SessionFactory sessionFactory) {

        // setup transaction manager based on session factory
        HibernateTransactionManager txManager = new HibernateTransactionManager();
        txManager.setSessionFactory(sessionFactory);

        return txManager;
    }

我只看一眼就能猜出你的错误。可以打开事务的日志级别以检查问题。限定符可以内联在方法参数中,以确保securitySessionFactory是autowired。

 类似资料: