[英]Java - Spring - Security not working due to transaction not detected
我正在嘗試構建一個帶有安全層的簡單 CRM spring 應用程序。
我的用例很簡單:登錄頁面允許訪問客戶列表並從中添加新用戶。
我為客戶管理創建了一個客戶端配置 class 和一個安全配置 class。 安全配置文件定義了它自己的數據源、事務管理器和 session 工廠以訪問管理用戶的專用數據庫:
@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;
//.....
}
我使用服務和 dao 層通過 hibernate 訪問用戶。
我的問題是,當我嘗試登錄或添加用戶時出現異常: 原因:javax.persistence.TransactionRequiredException:沒有事務正在進行
事情是使用事務注釋。 首先我通過controller go:
@Controller
public class LoginController {
@GetMapping("/showMyLoginPage")
public String showMyLoginPage() {
return "login";
}
@GetMapping("/access-denied")
public String showAccesDenied() {
return "access-denied";
}
}
然后是 jsp:
<form:form method="POST" action="${pageContext.request.contextPath}/authenticateTheUser">
用戶名:
密碼:
</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());
}
}
提交 jsp 時,它會調用用戶服務詳細信息(在配置類中自動裝配)和事務下的 loadUserByUsername 方法:
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 是自動裝配的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.