Spring登录表单示例 [英] Spring login form example
问题描述
我尝试在Google中搜索,但找不到任何用于验证用户名和密码的数据库。
更简单的话,我如何使用Spring和Hibernate创建一个简单的登录表单,其中用数据库检查凭证。
更新
凸轮任何人都会想出一个简单的例子,我可以看到流程如何以及输入数据是如何传递给hibernate的?
首先,您应该定义这个文件 WEB-INF / spring / serurity-context.xml
:
< beans:beans xmlns =http://www.springframework.org/ schema / security
xmlns:beans =http://www.springframework.org/schema/beansxmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation =http://www.springframework.org/schema/beans http://www.springframework.org/s chema / beans / spring-beans-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1。 XSD>
< http auto-config =true/>
< beans:bean id =myUserServiceclass =org.my.UserService/>
< authentication-provider user-service-ref =myUserService/>
< / beans:beans>
现在您应该创建 org.my.UserService
类并实现接口 org.springframework.security.core.userdetails.UserDetailsService
。这个接口有一个方法:
$ $ p $ UserDetails loadUserByUsername(String username)抛出UsernameNotFoundException,org.springframework.dao.DataAccessException
在这个方法中,您可以使用Hibernate来通过userName加载用户。如果用户不存在 - 只要抛出UsernameNotFoundException,否则返回新的初始化UserDetails实例(在那里你可以提供很多东西,比如用户角色,账户到期日期等等)。
现在出现 web.xml
:
< web-app xmlns =http://java.sun.com/xml/ns/javaee
xmlns:xsi =http:// www .w3.org / 2001 / XMLSchema-instance
xsi:schemaLocation =http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee /web-app_2_5.xsd
version =2.5>
< display-name>我的Web应用程式< / display-name>
< context-param>
< param-name> contextConfigLocation< / param-name>
< param-value>
/WEB-INF/spring/*-context.xml
< / param-value>
< / context-param>
< filter>
< filter-name> springSecurityFilterChain< / filter-name>
< filter-class> org.springframework.web.filter.DelegatingFilterProxy< / filter-class>
< / filter>
< filter-mapping>
< filter-name> springSecurityFilterChain< / filter-name>
< url-pattern> / *< / url-pattern>
< / filter-mapping>
< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener< / listener-class>
< / listener>
< servlet>
< servlet-name>调度程序< / servlet-name>
< servlet-class> org.springframework.web.servlet.DispatcherServlet< / servlet-class>
1< / load-on-startup>
< / servlet>
< servlet-mapping>
< servlet-name>调度程序< / servlet-name>
< url-pattern> / *< / url-pattern>
< / servlet-mapping>
< / web-app>
如果您有任何问题或出现问题,请随时询问:)
$ b:b PS:因此,使用UserDetailsService时,您不必检查用户帐户是否处于活动状态等的密码。您只需提供有关用户的spring-security信息,并提供 userName
和框架验证用户本身。例如,如果你使用MD5编码你的密码,比你可以使用 password-encoder
这样:
< beans:bean id =myUserServiceclass =org.my.UserService/>
< authentication-provider user-service-ref =myUserService>
< password-encoder hash =md5/>
< / authentication-provider>
更新
现在我们会潜入更多深入 UserService
- 我的(简化的)真实世界示例。
UserService
class:
import org.my_company.my_app.domain.User
public class UserService实现UserDetailsService {
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
$ b $ public UserDetails loadUserByUsername(String username)抛出UsernameNotFoundException,DataAccessException {
//载入用户
User user = userDao.getUser(username);
if(user!= null){
//转换角色
List< GrantedAuthority> roles = new ArrayList< GrantedAuthority>();
for(Privilege p:user.getPrivileges()){
roles.add(new GrantedAuthorityImpl(p.getName()));
$ b $ //初始化用户
SecurityUser securityUser = new SecurityUser(
user.getUsername(),
user.getLdapAuth()?getLdapPassword(user .getUsername()):user.getPassword(),
user.getStatus()!= User.Status.NOT_COMMITED,user.getStatus()!= User.Status.BLOCKED,true,true,
roles.toArray(new GrantedAuthority [0])
);
securityUser.setUser(user);
返回securityUser;
} else {
throw new UsernameNotFoundException(No user with username'+ username +'found!);
$ / code $ / pre
现在 SecurityUser
: import org.my_company.my_app.domain.User
public class SecurityUser extends org.springframework.security.core.userdetails.User {
private用户用户;
public User getUser(){
return user;
}
public void setUser(User user){
this.user = user;
$ b $ public SecurityUser(String username,String password,boolean enabled,boolean accountNonExpired,boolean credentialsNonExpired,boolean accountNonLocked,GrantedAuthority [] authorities)throws IllegalArgumentException {
super(username,密码,启用,accountNonExpired,credentialsNonExpired,accountNonLocked,权限);
最后 UserDao code>:
import org.my_company.my_app.domain.User
public class UserDao扩展了HibernateDaoSupport {
public User getUser(String username){
List users = getHibernateTemplate()。find(from User where username =?,username);
返回用户== null || users.size()<= 0? null :(用户)users.get(0);
code
$ b你可以看到我用 HibernateTemplate
这里。
I tried searching in Google, but I could not find any good examples where a username and password are checked with a database for authentication purposes.
In further simple words, how can I create a simple login form using Spring and Hibernate where the credentials are checked with the database.
Update
Cam anyone come up with a simple example where I can see how the flow goes and how the input data is passed to hibernate?
解决方案 At first you should define this file WEB-INF/spring/serurity-context.xml
:
<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-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd">
<http auto-config="true" />
<beans:bean id="myUserService" class="org.my.UserService" />
<authentication-provider user-service-ref="myUserService" />
</beans:beans>
Now you should create org.my.UserService
class and implement interface org.springframework.security.core.userdetails.UserDetailsService
. This interface has one method:
UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, org.springframework.dao.DataAccessException
And in this method you can use Hibernate in order to load user by userName. If user does not exists - just throw UsernameNotFoundException, otherwise return new intialized UserDetails instance (there you can provide a lot of stuff like user roles, account expiration date, etc...).
Now comes web.xml
:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>My Webapp</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/*-context.xml
</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
If you have any questions or something goes wrong, feel free to ask :)
PS: So with UserDetailsService you don't have to check password of whether user account is active, etc. You just provide spring-security information about user with provided userName
and framework validates user itself. If you encode your passwords with MD5 for example, than you can use password-encoder
like this:
<beans:bean id="myUserService" class="org.my.UserService" />
<authentication-provider user-service-ref="myUserService">
<password-encoder hash="md5"/>
</authentication-provider>
Update
Now we will dive more deeper in UserService
- my (simplified) real world example.
UserService
class:
import org.my_company.my_app.domain.User
public class UserService implements UserDetailsService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
// load user
User user = userDao.getUser(username);
if (user != null) {
// convert roles
List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();
for (Privilege p : user.getPrivileges()) {
roles.add(new GrantedAuthorityImpl(p.getName()));
}
// initialize user
SecurityUser securityUser = new SecurityUser(
user.getUsername(),
user.getLdapAuth() ? getLdapPassword(user.getUsername()) : user.getPassword(),
user.getStatus() != User.Status.NOT_COMMITED, user.getStatus() != User.Status.BLOCKED, true, true,
roles.toArray(new GrantedAuthority[0])
);
securityUser.setUser(user);
return securityUser;
} else {
throw new UsernameNotFoundException("No user with username '" + username + "' found!");
}
}
}
Now SecurityUser
:
import org.my_company.my_app.domain.User
public class SecurityUser extends org.springframework.security.core.userdetails.User {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public SecurityUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, GrantedAuthority[] authorities) throws IllegalArgumentException {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
And finally UserDao
:
import org.my_company.my_app.domain.User
public class UserDao extends HibernateDaoSupport {
public User getUser(String username) {
List users = getHibernateTemplate().find("from User where username = ?", username);
return users == null || users.size() <= 0 ? null : (User) users.get(0);
}
}
As you can see I used HibernateTemplate
here.
这篇关于Spring登录表单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!