关于使用Hibernate进行SpringSecurity3数据库身份验证和springsecurity数据库认证的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java–使用RestTe
关于使用Hibernate进行Spring Security 3数据库身份验证和springsecurity数据库认证的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于java – 使用RestTemplate的Spring Security身份验证、java – 使用Spring Security对Facebook进行身份验证、jsf-2 – 如何在JSF表单中执行Spring Security身份验证、Spring BatchJpaItemWriter与HibernateItemWriter以及为什么使用HibernateItemWriter时为什么需要HibernateTransactionManager等相关知识的信息别忘了在本站进行查找喔。
本文目录一览:- 使用Hibernate进行Spring Security 3数据库身份验证(springsecurity数据库认证)
- java – 使用RestTemplate的Spring Security身份验证
- java – 使用Spring Security对Facebook进行身份验证
- jsf-2 – 如何在JSF表单中执行Spring Security身份验证
- Spring BatchJpaItemWriter与HibernateItemWriter以及为什么使用HibernateItemWriter时为什么需要HibernateTransactionManager
使用Hibernate进行Spring Security 3数据库身份验证(springsecurity数据库认证)
我需要从数据库对用户进行身份验证,Spring Security文档没有告诉您如何使用hibernate进行身份验证。那可能吗,我该怎么做?
答案1
小编典典您必须制作自己的自定义身份验证提供程序。
示例代码:
从Hibernate加载用户的服务:
import org.springframework.security.core.userdetails.UserDetails;import org.springframework.security.core.userdetails.UserDetailsService;import org.springframework.security.core.userdetails.UsernameNotFoundException;@Service("userDetailsService") public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserDao dao; @Autowired private Assembler assembler; @Transactional(readOnly = true) public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException { UserDetails userDetails = null; UserEntity userEntity = dao.findByName(username); if (userEntity == null) throw new UsernameNotFoundException("user not found"); return assembler.buildUserFromUserEntity(userEntity); }}
将您的实体转换为spring用户对象的服务:
import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.GrantedAuthorityImpl;import org.springframework.security.core.userdetails.User;@Service("assembler")public class Assembler { @Transactional(readOnly = true) User buildUserFromUserEntity(UserEntity userEntity) { String username = userEntity.getName(); String password = userEntity.getPassword(); boolean enabled = userEntity.isActive(); boolean accountNonExpired = userEntity.isActive(); boolean credentialsNonExpired = userEntity.isActive(); boolean accountNonLocked = userEntity.isActive(); Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(); for (SecurityRoleEntity role : userEntity.getRoles()) { authorities.add(new GrantedAuthorityImpl(role.getRoleName())); } User user = new User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, id); return user; }}
基于命名空间的application-context-security.xml如下所示:
<http> <intercept-url pattern="/login.do*" filters="none"/> <intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <form-login login-page="/login.do" authentication-failure-url="/login.do?error=failed" login-processing-url="/login-please.do" /> <logout logout-url="/logoff-please.do" logout-success-url="/logoff.html" /></http><beans:bean id="daoAuthenticationProvider"> <beans:property name="userDetailsService" ref="userDetailsService"/></beans:bean><beans:bean id="authenticationManager"> <beans:property name="providers"> <beans:list> <beans:ref local="daoAuthenticationProvider" /> </beans:list> </beans:property></beans:bean><authentication-manager> <authentication-provider user-service-ref="userDetailsService"> <password-encoder hash="md5"/> </authentication-provider></authentication-manager>
java – 使用RestTemplate的Spring Security身份验证
现在,Web App 2需要访问Web App 1的服务.通常,我们将使用RestTemplate类向其他Web服务发出请求.
我们如何将Web App 2的请求中的认证凭证传递给Web App 1
解决方法
服务器 – 弹簧安全配置
<sec:http> <sec:intercept-url pattern="/**" access="ROLE_USER" method="POST"/> <sec:intercept-url pattern="/**" filters="none" method="GET"/> <sec:http-basic /> </sec:http> <sec:authentication-manager alias="authenticationManager"> <sec:authentication-provider> <sec:user-service> <sec:user name="${rest.username}" password="${rest.password}" authorities="ROLE_USER"/> </sec:user-service> </sec:authentication-provider> </sec:authentication-manager>
客户端RestTemplate配置
<bean id="httpClient"> <constructor-arg ref="httpClientParams"/> <property name="state" ref="httpState"/> </bean> <bean id="httpState"> <property name="credentials" ref="credentials"/> </bean> <bean id="credentials"> <constructor-arg value="${rest.username}"/> <constructor-arg value="${rest.password}"/> </bean> <bean id="httpClientFactory"> <constructor-arg ref="httpClient"/> </bean> <bean> <constructor-arg ref="httpClientFactory"/> </bean>
自定义HttpState实现
/** * Custom implementation of {@link HttpState} with credentials property. * * @author banterCZ */ public class CustomHttpState extends HttpState { /** * Set credentials property. * * @param credentials * @see #setCredentials(org.apache.commons.httpclient.auth.AuthScope,org.apache.commons.httpclient.Credentials) */ public void setCredentials(final Credentials credentials) { super.setCredentials(AuthScope.ANY,credentials); } }
Maven依赖
<dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>
java – 使用Spring Security对Facebook进行身份验证
所以我的问题是,如何使用Spring安全性对Facebook用户进行身份验证?
解决方法
jsf-2 – 如何在JSF表单中执行Spring Security身份验证
这是login.xhtml中的表单元素
<h:form> <h:outputLabel value="User Id:" for="userId"/> <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" > </h:inputText> <h:outputLabel value="Password: " for ="password"/> <h:inputSecret id="j_password" value="#{loginBean.password}" /> <h:commandButton value="Submit" action="#{j_spring_security_check}" /> </h:form>
但渲染的html页面有类似下面的内容.看一下表单操作和输入标签的名称
表单元素
<form id="j_idt6" name="j_idt6" method="post" action="/jsfproject2/faces/login.xhtml" enctype="application/x-www-form-urlencoded">
和输入标签
User Id:</label><input id="j_idt6:j_username" type="text" name="j_idt6:j_username" />
现在我希望表单操作为/ j_spring_security_check,输入框为’j_username’和j_password
我们怎样才能做到这一点?
解决方法
在JSF表单上使用prependId =“false”
如< h:form>是一个命名容器,它为其子级的id添加了指定的id或自动生成的id,因此Spring Security期望id保持unchainged,只是不要添加id:
<h:form prependId="false"> <h:outputLabel value="User Id: " for="userId" /> <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" /> <h:outputLabel value="Password: " for ="password" /> <h:inputSecret id="j_password" value="#{loginBean.password}" /> <h:commandButton value="Submit" action="#{loginBean.login}" /> </h:form>
请注意,#{j_spring_security_check}是一个错误的操作方法:它需要是#{loginBean.login},其中包含以下内容:
public String login() { //do any job with the associated values that you've got from the user,like persisting attempted login,etc. FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext extenalContext = facesContext.getExternalContext(); Requestdispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestdispatcher("/j_spring_security_check"); dispatcher.forward((ServletRequest)extenalContext.getRequest(),(ServletResponse)extenalContext.getResponse()); facesContext.responseComplete(); return null; }
基本上,您需要做的就是调度到/ j_spring_security_check并将j_username和j_password作为请求参数.
使用纯HTML表单
基本上,在这个问题上没有特别需要混淆JSF表单,以防除了身份验证之外你不需要做一些额外的事情,而纯HTML表单足以让Spring Security完成它的工作.
<form action="/j_spring_security_check" method="POST"> <label for="j_username">User Id: </label> <input id="j_username" name="j_username" type="text" /> <label for="j_password">Password: </label> <input id="j_password" name="j_password" type="password"/> <input type="submit" value="Submit"/> </form>
Spring BatchJpaItemWriter与HibernateItemWriter以及为什么使用HibernateItemWriter时为什么需要HibernateTransactionManager
我正在使用Spring Boot项目进行Spring
Batch。我的问题是,当我使用HibernateItemWriter时,为什么需要LocalSessionFactoryBean的HibernateTransactionManager和SessionFactory?
应用程序
import java.util.Properties;import javax.sql.DataSource;import org.hibernate.SessionFactory;import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.orm.hibernate5.HibernateTransactionManager;import org.springframework.orm.hibernate5.LocalSessionFactoryBuilder;import org.springframework.transaction.PlatformTransactionManager;@SpringBootApplication@EnableBatchProcessingpublic class Application {public static void main(String[] args) throws Exception { SpringApplication.run(Application.class, args);}@Beanpublic PlatformTransactionManager transactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory(null)); return transactionManager;}@Beanpublic SessionFactory sessionFactory(DataSource datasource) { Properties properties = new Properties(); properties.setProperty("hibernate.show_sql", "true"); properties.setProperty("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); return new LocalSessionFactoryBuilder(datasource).scanPackages("hello") .addProperties(properties) .buildSessionFactory();}}
BatchConfiguration.java
import org.hibernate.SessionFactory;import org.springframework.batch.core.Step;import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;import org.springframework.batch.core.configuration.annotation.StepScope;import org.springframework.batch.item.ItemWriter;import org.springframework.batch.item.database.HibernateItemWriter;import org.springframework.batch.item.file.FlatFileItemWriter;import org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor;import org.springframework.batch.item.file.transform.DelimitedLineAggregator;import org.springframework.batch.item.file.transform.FieldExtractor;import org.springframework.batch.item.file.transform.LineAggregator;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.io.FileSystemResource;import org.springframework.transaction.PlatformTransactionManager;import org.springframework.web.client.RestTemplate;@Configurationpublic class BatchConfiguration {@Autowiredpublic JobBuilderFactory jobBuilderFactory;@Autowiredpublic StepBuilderFactory stepBuilderFactory;@Autowiredpublic RestTemplate restTemplate;@Autowiredpublic PlatformTransactionManager tManager;@Value("${file.name}")public String fileName;@Bean@StepScopepublic RestItemReader reader2() { return new RestItemReader(restTemplate);}@Beanpublic PersonItemProcessor processor() { return new PersonItemProcessor();}@Beanpublic HibernateItemWriter<Person> hibernateWriter(SessionFactory emf) { HibernateItemWriter<Person> writer = new HibernateItemWriter<>(); writer.setSessionFactory(emf); return writer;}@Beanpublic Step step1() { return stepBuilderFactory.get("step1") .transactionManager(tManager) .<KarvyFundInfoModel, Person> chunk(2) .reader(reader2()) .processor(new PersonItemProcessor()) .writer(hibernateWriter(null)) .build();}}
这是因为如果我不包含它,并通过使用以下代码从EntityManagerFactory获取SessionFactory的原因
EntityManagerFactory.unwarp(SessionFactory.class);
我将收到“没有正在进行的交易”错误。但是,当我使用JpaItemWriter时,情况并非如此。
但是基于我对Spring Batch的理解,在块处理中,已经提供了默认的事务管理器。
为了使用HibernateItemWriter,是否必须从LocalSessionFactoryBean(来自hibernate)提供HibernateTransactionManager和SessionFactory?
而且,JpaItemWriter和HibernateItemWriter之间的主要区别是什么?我已经做过关于这两个方面的研究,Jpa是关于如何通过使用批注方式指定实体等的规范,而hibernate是Jpa的实现之一。不过,我对此并不十分清楚。hibernate是否比默认的jpa具有更多功能?例如SearchCriteria等?
答案1
小编典典为什么在使用HibernateItemWriter时需要LocalSessionFactoryBean的HibernateTransactionManager和SessionFactory
默认情况下,如果提供DataSource
bean,Spring
Batch将使用DataSourceTransactionManager
来管理事务。该事务管理器对您的JPA
/hibernate上下文一无所知。因此,HibernateItemWriter
在Session
后台使用Hibernate 的并没有“意识到”DataSourceTransactionManager
。因此,错误:no transaction is in progress
。
这HibernateTransactionManager
就是使Hibernate Session
参与Spring托管事务的原因。
JpaItemWriter和HibernateItemWriter之间的主要区别是什么?
在JpaItemWriter
使用JPA的API(EntityManagerFactory
和EntityManager
)写的项目。它不使用任何JPA提供程序特定的API。这样就可以在不更改编写器的情况下切换JPA提供程序。
在HibernateItemWriter
在另一侧使用Hibernate特定API(SessionFactory
和Session
)和特定于仅hibernate。该组件对于直接使用hibernate而不使用JPA的应用程序很有用。您可能具有相同的编写器,但对于另一个JPA提供程序,例如,OpenJpaItemWriter
或EclipseLinkItemWriter
使用这些提供程序中的特定API。
今天关于使用Hibernate进行Spring Security 3数据库身份验证和springsecurity数据库认证的讲解已经结束,谢谢您的阅读,如果想了解更多关于java – 使用RestTemplate的Spring Security身份验证、java – 使用Spring Security对Facebook进行身份验证、jsf-2 – 如何在JSF表单中执行Spring Security身份验证、Spring BatchJpaItemWriter与HibernateItemWriter以及为什么使用HibernateItemWriter时为什么需要HibernateTransactionManager的相关知识,请在本站搜索。
本文标签: