Spring login form example

I tried to search on Google, but did not find any good examples where the username and password are verified using a database for authentication purposes.

In the following simple words, how can I create a simple login form using Spring and Hibernate, where credentials are verified using a database.

Update

Anyone come up with a simple example where I can see how the stream is going and how the input is transferred to sleep mode?

+23
java spring-mvc spring-security hibernate
Jan 6 2018-11-11T00:
source share
7 answers

First you must 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 must create the org.my.UserService class and implement the org.springframework.security.core.userdetails.UserDetailsService interface. This interface has one method:

 UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, org.springframework.dao.DataAccessException 

And in this method, you can use Hibernate to load the user by username. If the user does not exist, just throw a UsernameNotFoundException, otherwise return a new, initialized instance of UserDetails (there you can provide many things, such as user roles, account expiration dates, 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 is wrong, feel free to ask :)

PS: Thus, with UserDetailsService you do not need to check the password, whether the user account is active, etc. You simply provide spring security information for the user with the provided userName , and the user checks the environment. If you, for example, encode your passwords using MD5, you can use password-encoder as follows:

 <beans:bean id="myUserService" class="org.my.UserService" /> <authentication-provider user-service-ref="myUserService"> <password-encoder hash="md5"/> </authentication-provider> 

Update

Now we UserService deeper into 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 the HibernateTemplate here.

+27
Jan 23 '11 at 20:35
source share

You can go to the Spring example login form here: http://www.roseindia.net/spring/spring-mvc-login-example.shtml .

+8
Jan 6 '11 at 10:01
source share

The main xml configuration you can see in the "Easy Angle" post. The part that he referred to as "myUserService" is a bean that implements "UserDetailService" This basically has only one implementation method, which is as follows

 public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException 

If you use Spring, then you will likely have a Bean that handles access to your user table. This, which you can simply enter into this class to get user information, for example:

  @Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException, DataAccessException { UserTable user = userbean.getUserbyName(name); if (user == null) { throw new UsernameNotFoundException("User " + name + " not found!"); } Collection<GrantedAuthority> auth = getAuthorities(user.getAuthorities()); return new User(user.getName(), user.getPassword(), true, true, true, true, auth); } 

Now in bean authentication you only need to enter this bean and request it for UserDetails. There you can use it to verify that the credentials are correct and, if so, fill out the SecurityContext with the necessary login information.

  @Override public Boolean authenticate(String username, String password) { UserDetails userdetail = null; try { userdetail = myUserService.loadUserByUsername(username); } catch (UsernameNotFoundException e) { return false; } catch (DataAccessException e) { return false; } if (!myUserService.encodePassword(password).equals(userdetail.getPassword())) { return false; } Authentication auth = new UsernamePasswordAuthenticationToken(userdetail.getUsername(), userdetail.getPassword(), userdetail.getAuthorities()); SecurityContext sc = new SecurityContextImpl(); ServletRequestAttributes attr = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes(); attr.getRequest().getSession().setAttribute(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY, userdetail.getUsername()); sc.setAuthentication(auth); SecurityContextHolder.setContext(sc); return true; } 

Of course, this is a simplified version of the real one. There are a few more checks that you should perform before saying that the user is authenticated (e.g. SQLInjection)

+5
Jan 24 '11 at 11:14
source share

App-fuse will provide you with a complete working example: http://appfuse.org/display/APF/AppFuse+QuickStart

Or, if you installed maven, just run:

 mvn archetype:generate -B -DarchetypeGroupId=org.appfuse.archetypes -DarchetypeArtifactId=appfuse-light-spring-security-archetype -DarchetypeVersion=2.1.0-M2 -DgroupId=com.mycompany -DartifactId=myproject 

This will lead to the creation of a light light appfuse project using spring mvc, spring security and sleep mode.

+3
Jan 21 '11 at 12:53 on
source share

If you are using a database that can be accessed using JDBC, you do not need to create your own authentication provider. The authentication provider already allows you to query the database directly. It will reduce the required code to 9 lines of XML instead of many classes.

I answered this here with code samples: Spring Security Database Authentication 3 with Hibernate

+1
Apr 02 '14 at 17:54 on
source share

The link below will definitely give you what you are looking for. There is a login page that accepts a user ID and password. The password is stored in plain text, as this is just a test project. The database uses MySQL. You can check the steps, download the code and the war file from the link below. Let me know if you have problems launching the application. Hope it helps! http://badalchowdhary.wordpress.com/2012/02/26/spring-hibernate-integration/

0
Mar 05 '12 at 3:21
source share

Hey, here is a link to my GIT repository. I created a simple login form that verifies the username and password using SPring-MVC and Spring-JDBC.

https://github.com/gauravbhagat619/LoginCrud.git

0
Apr 26 '19 at 6:29
source share



All Articles