spring 3.x standard library
spring security web
spring security core
spring security config
First create a mysql database called loginexample. The sql code is as following.
CREATE TABLE `users` (`USER_ID` INT(10) UNSIGNED NOT NULL,`USERNAME` VARCHAR(45) NOT NULL,`PASSWORD` VARCHAR(45) NOT NULL,`ENABLED` tinyint(1) NOT NULL,PRIMARY KEY (`USER_ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_roles` (`USER_ROLE_ID` INT(10) UNSIGNED NOT NULL,`USER_ID` INT(10) UNSIGNED NOT NULL,`AUTHORITY` VARCHAR(45) NOT NULL,PRIMARY KEY (`USER_ROLE_ID`),KEY `FK_user_roles` (`USER_ID`),CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`USER_ID`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO users (USER_ID, USERNAME,PASSWORD, ENABLED)VALUES (100, 'madhumal', '123456', TRUE);
INSERT INTO.user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)VALUES (1, 100, 'ROLE_ADMIN')
INSERT INTO users (USER_ID, USERNAME,PASSWORD, ENABLED)VALUES (101, 'user', '123456', TRUE);
INSERT INTO user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)VALUES (2, 101, 'ROLE_USER')
Note that we have two user roles, admin and user.
Create a Dynamic web project with the name SpringLogin
create your mvc-dispatcher-servlet.xml in WEB-INF folder
put the following code in there
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="mad.springlogin" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/loginexample" />
<property name="username" value="root" />
<property name="password" value="pass" />
</bean>
</beans>
Now create the spring-security.xml in WEB-INF folder. put the following code there.
<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.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true">
<intercept-url pattern="/welcome*" access="ROLE_USER,ROLE_ADMIN" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="
select username,password, enabled
from users where username=?"
authorities-by-username-query="
select u.username, ur.authority from users u, user_roles ur
where u.user_id = ur.user_id and u.username =? "
/>
</authentication-provider>
</authentication-manager>
</beans:beans>
Note that we have two user roles indicated that has the accessing permission for /welcome* url patterns.
Then we have to configure the web.xml file for the security. Now update the web.xml to have the following code.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SpringLogin</display-name>
<!-- Spring MVC -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Then create a login.jsp in WEB-INF/pages folder. put the following in there
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
</head>
<body onload='document.f.j_username.focus();'>
<h3>Login with Username and Password (Custom Page)</h3>
<c:if test="${not empty message}">
<div>
${message}<br />
</div>
</c:if>
<c:if test="${not empty error}">
<div>
Your login attempt was not successful, try again.<br />
</div>
</c:if>
<form name='f' action="<c:url value='j_spring_security_check' />"
method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='j_username' value=''>
</td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password' />
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" />
</td>
</tr>
<tr>
<td colspan='2'><input name="reset" type="reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
Now we need a controller servlet to authenticate the user create a LoginController.java class and put the following code.
package mad.springlogin.controller;
import java.security.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class LoginController {
@RequestMapping(value="/welcome", method = RequestMethod.GET)
public String printWelcome(ModelMap model, Principal principal ) {
String name = principal.getName();
model.addAttribute("username", name);
model.addAttribute("message", "Spring Security Custom Form example");
return "hello";
}
@RequestMapping(value="/login", method = RequestMethod.GET)
public String login(ModelMap model) {
return "login";
}
@RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
model.addAttribute("error", "true");
return "login";
}
@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
model.addAttribute("message","successfully logged out !!!");
return "login";
}
}
Note that the data source is defined and we are using a data base called loginexample. This is the page a user will see when he is successfully authenticated.
create a hello.jsp file in WEB-INF/pages folder. put the following code.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
<h3>Message : ${message}</h3>
<h3>Username : ${username}</h3>
<a href='<c:url value="/j_spring_security_logout" />' > Logout</a>
</body>
</html>
Note that j_spring_security_logout will make the user logout.
Now you can use the localhost:8080/SpringLogin/welcome to test the code.
No comments:
Post a Comment