Tuesday 15 October 2013

Spring Security Login Using Hibernate Example

Spring Security with Authentication


First you need to create table in following structure

create table user_info( 
                       user_name varchar(50),
                       passwd varchar(200),
                       enabled int(1),
                       authority varchar(50) 
                     );

insert into user_info values('jayesh','password',1,'ROLE_USER');

you need to create a file named Spring-security.xml if not exists.
if you have the file than use below code to set up the spring log in configuration.
Spring-security.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-3.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/resources/**" security="none" />

 <http auto-config="true" use-expressions="true">
  <intercept-url pattern="/login*" access="permitAll" /> 
  <intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
  
 <form-login login-page="/login" authentication-failure-url="/loginfailed" default-target-url="/Home/"  />
  <logout logout-url="/logout" logout-success-url="/login"  invalidate-session="true"  />
  <session-management >
  <concurrency-control max-sessions="1" expired-url="/loginExp" />
  </session-management>
 </http>
 
 <authentication-manager>
 
  <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"

        users-by-username-query="
        select user_name,passwd,enabled
        from user_info where user_name=?"

        authorities-by-username-query="
        select user_name,authority from user_info         
        where user_name =?  " />
  </authentication-provider> 
  
 </authentication-manager>

 
</beans:beans>
 
 
login.jsp
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<html>
<head>
<title>Spring 3 MVC  - Spring Authentication Example</title>
</head>
<body>  
 <form action="j_spring_security_check" method="POST"> 
 
  UserName: <input type="text" name="j_username" /> 
 
  Password: <input type="password" name="j_password" />
  
  <input type="submit" value="Login" />
 
 </form>
</body>
</html>
 

No comments:

Post a Comment