spring security的配置和方法_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > spring security的配置和方法

spring security的配置和方法

 2012/4/10 13:52:58  yang02301  程序员俱乐部  我要评论(0)
  • 摘要:记得有位坛友在回复《学习Acegi-认证(authentication)》http://www.iteye.com/topic/52975时提到Spring已经集成Acegi认证,先将实例奉上。1)新建WebProject“MyE_spring_security”2)加入Spring3.0core,aop,persistence,web,securitylibrary3)创建com.proj.controller.LoginController.javapackagecom.proj
  • 标签:方法 配置 Spring
记得有位坛友在回复《学习Acegi-认证(authentication)》http://www.iteye.com/topic/52975时提到Spring已经集成Acegi认证,先将实例奉上。

1)新建WebProject “MyE_spring_security”

2)加入Spring3.0 core, aop, persistence, web, security library

3)创建com.proj.controller.LoginController.java
package com.proj.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) {

		return "login";

	}

}


4)创建users表,SQL:
CREATE TABLE IF NOT EXISTS `users` (
  `USERNAME` varchar(50) NOT NULL,
  `PASSWORD` varchar(50) NOT NULL,
  `ENABLED` bit(1) NOT NULL,
  PRIMARY KEY (`USERNAME`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `users` (`USERNAME`, `PASSWORD`, `ENABLED`) VALUES
('liuyxit', '123', b'1'),
('user1', 'user1', b'1'),
('user2', 'user2', b'1'),
('user4', 'user4', b'1'),
('user3', 'user3', b'1');


5)创建authorities表,SQL:
CREATE TABLE IF NOT EXISTS `authorities` (
  `USERNAME` varchar(50) NOT NULL,
  `AUTHORITY` varchar(50) NOT NULL,
  KEY `FK_AUTHORITIES_USERS` (`USERNAME`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `authorities` (`USERNAME`, `AUTHORITY`) VALUES
('liuyxit', 'ROLE_SUPERVISOR'),
('user1', 'ROLE_USER'),
('user2', 'ROLE_USER'),
('user3', 'ROLE_USER ');


6)加入MySQL connector java jar

7)创建WEB-INF/pages/hello.jsp:
<%@ 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>


8)创建WEB-INF/pages/login.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.errorblock {
	color: #ff0000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
	<h3>Login with Username and Password (Custom Page)</h3>

	<c:if test="${not empty error}">
		<div class="errorblock">
			Your login attempt was not successful, try again.<br /> Caused :
			${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
		</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>


9)创建WEB-INF/mvc-dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<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.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan base-package="com.proj.controller" />

	<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>

</beans>


10)创建WEB-INF/spring-database.xml
<beans xmlns="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">

	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName">
			<!-- 请自行修改为对应你的数据库的驱动类 -->
			<value>com.mysql.jdbc.Driver</value>
		</property>
		<property name="url">
			<!-- 请自行修改为对应你的数据库URL -->
			<value>jdbc:mysql://localhost/play_test</value>
		</property>
		<property name="username">
			<value>root</value>
		</property>
		<property name="password">
			<value>root</value>
		</property>
	</bean>

</beans>


11)创建WEB-INF/spring-security.xml
<?xml version="1.0" encoding="UTF-8"?>
	
<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.0.3.xsd"
	default-autowire="byName" default-lazy-init="true">

	<http auto-config="true">
		<intercept-url pattern="/welcome*" access="ROLE_USER" />
		<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 username,AUTHORITY FROM authorities 
		        WHERE username = ? " 
  			/>
		</authentication-provider>
	</authentication-manager>

</beans:beans>


12)创建WEB-INF/web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">

	<display-name>Spring MVC Application</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
			/WEB-INF/spring-database.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>
	
</web-app>



13)运行,输入 username user1, password user1



  • MyE_spring_security.zip (447 KB)
  • 下载次数: 0
发表评论
用户名: 匿名