1.pom代码引入spring security 4.0
<!-- spring security --> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-core</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>4.0.0.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>4.0.0.RELEASE</version> </dependency>
2.web.xml配置spring security过滤器
<?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" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="schedule-console" version="3.0"> <display-name>source</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-*.xml</param-value> </context-param> <!-- spring mvc --> <servlet> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <!-- 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> <!-- sessionInView --> <filter> <filter-name>SpringOpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>SpringOpenSessionInViewFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> </web-app>
3.spring-security.xml配置文件访问权限、登录界面、推出登录后的地址、验证的数据库源。我的datasource在 spring hibernate中,不多说这些
<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-4.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd"> <http pattern="/**/*.js" security="none"/> <http pattern="/**/*.css" security="none"/> <http pattern="/**/*.png" security="none"/> <http pattern="/**/*.jpg" security="none"/> <http pattern="/**/*.ico" security="none"/> <http> <intercept-url pattern="/configAction/getConfig.action" access="permitAll" /> <intercept-url pattern="/login.jsp" access="permitAll" /> <intercept-url pattern="/**" access="authenticated" /> <form-login login-page="/login.jsp" authentication-failure-url="/login.jsp" default-target-url="/index.jsp" /> <logout logout-success-url="/login.jsp" /> </http> <authentication-manager> <authentication-provider> <jdbc-user-service data-source-ref="dataSource"/> <!-- <password-encoder hash="md5"></password-encoder> --> </authentication-provider> </authentication-manager> </beans:beans>
4.extjs的登录界面,用html写界面也差不多,注意用username、password、csrf就可以了。用html写表单更简单
Ext.onReady(function(){ Ext.create('Ext.window.Window',{ viewModel:Ext.create("app.view.ViewModel",{url:"configAction/getConfig.action"}), bind: {title:"{systemName}"}, width:470, height:280, modal:true, titleAlign:"center", closable:false, resizable:false, autoShow:true, buttonAlign:"center", border:false, defaults:{border:false}, buttons:[{ text:lang("Login"), name:"submitButton", listeners:{ click:function(button){ var formPanel=button.up("window").down("form"); if(formPanel.getForm().isValid()){ formPanel.submit(); }else{ button.up("window").down("panel[name='errMsgPanel']").update('请填写用户名和密码'); } } } }], items:[{ height:60, bodyStyle:{"background":"url(images/main/banner.jpg)","background-size":"100% 100%"}, items:[{ xtype:"image", src:'images/main/logo.png', height:60 }] },{ xtype:"form", standardSubmit:true, bodyPadding:"30 0 0 40", url:"login", bodyStyle:{"background":"none"}, items:[{ xtype:"hidden", name:"${_csrf.parameterName}", value:"${_csrf.token}" },{ xtype:"textfield", labelAlign:"right", fieldLabel:lang("Username"), name:"username", allowBlank:false, labelWidth:60, width:320, labelStyle:"font-weight:bold", emptyText:lang("Please enter user name"), fieldStyle:"background:url(images/icon/user.png) #fff 3px 3px no-repeat;padding-left:22px;" },{ xtype:"textfield", inputType:'password', style:"margin-top:15px", labelAlign:"right", fieldLabel:lang("Password"), name:"password", allowBlank:false, labelWidth:60, width:320, labelStyle:"font-weight:bold", emptyText:lang("Please enter password"), fieldStyle:"background:url(images/icon/password.png) #fff 3px 3px no-repeat;padding-left:22px;", enableKeyEvents:true, listeners:{ keyup:function(cmp,e,obj){ var button=cmp.up("window").down("button[name='submitButton']"); if(e.getKey()==Ext.EventObject.ENTER)button.fireEvent("click",button); } } }] },{ xtype:"panel", name:"errMsgPanel", border:false, padding:"5", bodyStyle:{"background":"none","color":"red","text-align":"center","font-weight":"bold","font-size":"14px"}, html:lang("${param.error}${param.logout}") }], listeners:{ show:function(cmp,e){ cmp.down("textfield[name='username']").focus(); } } }); });
5.退出登录的方法,一定要csrf,除非你在配置文件中禁用csrf,用html写表单更简单
Ext.MessageBox.confirm('系统提示', '您确定要注销登录吗?',function(btn){ if(btn=="yes"){ var csrf=document.getElementsByName("csrf").item(0); var parameterName=csrf.attributes['parameterName'].value; var token=csrf.attributes['token'].value; Ext.create({ xtype:"form", standardSubmit:true, url:"logout", items:[{ xtype:"hidden", name:parameterName, value:token }] }).submit(); } });
6.附一下数据库登录必须要的两个表
# # Structure for table "authorities" # DROP TABLE IF EXISTS `authorities`; CREATE TABLE `authorities` ( `id` varchar(36) NOT NULL DEFAULT '', `username` varchar(50) NOT NULL DEFAULT '', `authority` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; # # Data for table "authorities" # INSERT INTO `authorities` VALUES ('a','admin','ROLE_USER'); # # Structure for table "users" # DROP TABLE IF EXISTS `users`; CREATE TABLE `users` ( `id` varchar(36) NOT NULL DEFAULT '', `username` varchar(50) DEFAULT NULL COMMENT '用户名', `password` varchar(100) DEFAULT NULL COMMENT '密码', `enabled` varchar(10) DEFAULT NULL COMMENT '禁用', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户'; # # Data for table "users" # INSERT INTO `users` VALUES ('a','admin','123456','true');
7.其他的代码就不用你管了,登录操作session这些都是框架搞的,才发现很简单,但只是学spring security的开始。