我试图建立一个简单的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
@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。
securityconfig.java
我想将我的项目迁移到空安全,但是dependecie不支持空安全:
请说出这段代码有什么问题。
我是一个新的Spring和学习的事务概念。无法使@Transactional工作。 用例: 当getEmployee()抛出RuntimeException时,员工和员工详细信息的数据插入应该回滚。但回滚没有发生。我使用的是Oracle数据库11g和spring 4.3.1版本。下面是正在运行的独立java代码。
我正在使用MongoDB的springboot 2.3.0。注释对我不起作用。如果发生异常,则无法回滚事务。 任何帮助都将得到高度赞赏。 我的控制器类: 我的serviceImpl类 我的MongoConfig类
类似于这里的问题。我的测试不稳定。尝试并捕获解决方案在这里不起作用。有解决这个问题的最佳实践吗?