首先,先把项目的整体结构以及整体配置贴出来,后面介绍中会将其中的功能模块一个一个的细讲解,稍安勿躁,一步一步的往下看:
本例使用springMVC+spring security进行测试,需要导入的jar包:
项目基本结构:
环境搭建,主要是三个配置文件:web.xml, applicationContext.xml, springmvc-security.xml 以及 springmvc-servlet.xml
1,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>display-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>
classpath:properties/applicationContext.xml,
classpath:properties/springmvc-security.xml
param-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<filter>
<filter-name>characterFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>springSecurityFilterChainfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
<filter-name>springSecurityFilterChainfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:properties/springmvc-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>*.actionurl-pattern>
servlet-mapping>
web-app>
二,applicationContext.xml
xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:property-placeholder location="classpath:properties/jdbc.properties"/>
<context:component-scan base-package="com.springsecurity">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${druid.url}" />
<property name="username" value="${druid.username}" />
<property name="password" value="${druid.password}" />
<property name="maxActive" value="${druid.maxActive}" />
<property name="minIdle" value="${druid.minIdle}" />
<property name="maxWait" value="${druid.maxWait}" />
<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
<property name="connectionProperties" value="config.decrypt=true" />
<property name="filters" value="config,stat,wall,log4j" />
bean>
beans>
三,springmvc-servlet.xml
xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<context:component-scan base-package="com.springsecurity.action" />
<mvc:resources location="/resources/" mapping="/resources/**" />
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1">property>
<property name="defaultContentType" value="text/html" />
<property name="ignoreAcceptHeader" value="true">property>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
map>
property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
bean>
list>
property>
bean>
beans>
四,springmvc-security.xml(以下是一个完整的配置,在后面介绍中会对其中的功能拆开讲解,并对某些逐步深入)
xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:debug/>
<security:http pattern="/images/**" security="none"/>
<security:http pattern="/js/**" security="none" />
<security:http pattern="/index.jsp" security="none" />
<security:http use-expressions="true" access-denied-page="/WEB-INF/pages/common/noAuth.jsp">
<security:expression-handler ref="expressHandler"/>
<security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/common/loginPage.action"
authentication-failure-url="/common/failure.action"
default-target-url="/main/main.action"
username-parameter="username" password-parameter="password"/>
<security:logout logout-url="/securitylogout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/user/logout.action" />
<security:remember-me key="myspringsecurity" data-source-ref="dataSource"
token-validity-seconds="3600000" remember-me-parameter="rememberme" />
<security:session-management>
<security:concurrency-control error-if-maximum-exceeded="true" max-sessions="10"/>
security:session-management>
<security:intercept-url pattern="/main/delete.action" access="hasRole('ROLE_ADMIN')"/>
security:http>
<security:authentication-manager alias="theAuthenticationManager">
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource" id="jdbcUserService"
users-by-username-query="select username,password,enabled from user where username = ?"
authorities-by-username-query="select username, authority from user where username = ?"
role-prefix="ROLE_"/>
<security:password-encoder ref="passwordEncoder">
<security:salt-source user-property="username"/>
security:password-encoder>
security:authentication-provider>
security:authentication-manager>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
bean>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:properties/myMessage_zh_CN" />
bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver" />
<bean id="rememberMeAuthenticationFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<constructor-arg index="0" ref="theAuthenticationManager"/>
<constructor-arg index="1" ref="rememberMeServices"/>
bean>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<constructor-arg index="0" value="myspringsecurity"/>
<constructor-arg index="1" ref="jdbcUserService"/>
<constructor-arg index="2" ref="tokenRepository"/>
bean>
<bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<constructor-arg value="myspringsecurity"/>
bean>
<bean id="tokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<property name="createTableOnStartup" value="false"/>
<property name="dataSource" ref="dataSource"/>
bean>
<bean id="roleHierarchy" class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
<property name="hierarchy" value="ROLE_ADMIN > ROLE_USER"/>
bean>
<bean id="expressHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
<property name="roleHierarchy" ref="roleHierarchy"/>
bean>
beans>
接下来的主要是对spring security的简单配置,分别通过userService以及dataSource来进行登录处理,权限控制,以及记住密码,权限层级,自定义过滤器等功能进行一一讲解,主要是针对springmvc-security.xml的文件配置进行讲解,上述的其他配置不需要修改:
Springmvc-security.xml中配置:
<security:http pattern="/images/**" security="none"/>
<security:http pattern="/js/**" security="none" />
<security:http pattern="/index.jsp" security="none" />
<security:http use-expressions="true" access-denied-page="/WEB-INF/pages/common/noAuth.jsp">
<security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/common/loginPage.action"
authentication-failure-url="/common/failure.action"
default-target-url="/main/main.action"
username-parameter="username" password-parameter="password"/>
security:http>
<security:authentication-manager alias="theAuthenticationManager">
<security:authentication-provider user-service-ref="userService" >
<security:password-encoder ref="passwordEncoder">
<security:salt-source user-property="username"/>
security:password-encoder>
security:authentication-provider>
security:authentication-manager>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder">
bean>
写一个service实现UserDetailsService:
public class UserService implements UserDetailsService{
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
//模拟从数据库中取出的用户名
//可以注入直接的业务层处理类来得到用户的用户名和密码
String dbUsername = "hwt";
String password = "123456";
//密码加密
String ecPd = new Md5PasswordEncoder().encodePassword(password, dbUsername);
UserDetails userDetails = new User(dbUsername, ecPd, true,true,true,true,getAuthorities(1));
return userDetails;
}
//定义用户权限,一个用户可以有多个权限,以下代码没有体现,可以自行实现
Private Collection
List
// 所有的用户默认拥有ROLE_USER权限
if (role == 0) {
authList.add(new SimpleGrantedAuthority("ROLE_USERS"));
}
// 如果参数role为1.则拥有ROLE_ADMIN权限
if (role == 1) {
authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
return authList;
}
}
并在springmvc-security.xml中实例化
<bean id="userService" class="com.springsecurity.service.UserService" />
登陆页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>logintitle>
head>
<body>
<div>登陆页面:div>
<div>
<form action="${pageContext.request.contextPath}/j_spring_security_check" method="post">
用户名:<input type="text" name="username" value=""/><br/>
密码:<input type="password" name="password" value="" /><br/>
记住我:<input type="checkbox" name="rememberme"/><br/>
<input type="submit" value="登陆"/>
form>
div>
body>
html>
还有一种通过xml配置权限来实现登陆,不使用userDetailService
<security:authentication-manager alias="theAuthenticationManager">
<security:authentication-provider>
<security:password-encoder ref="passwordEncoder">
<security:salt-source user-property="username"/>
security:password-encoder>
<security:user-service>
<security:user name="hwt" password="3ba941370bf5329ad9a714f404ed33e6" authorities="ROLE_USER,ROLE_ADMIN" />
<security:user name="kevin" password="f39084b3dc1be24f36b2494738197105" authorities="ROLE_USER" />
security:user-service>
security:authentication-provider>
security:authentication-manager>
本例采用MySQL,首先我们通过查看users-by-username-query以及authorities-by-username-query 的配置说明可以看出来我们有以下字段:username,password,enabled,authority
正常情况下,我们需要建立一个用户表,用户角色表,角色表,但是为了简单演示,我就建立了一个表,包括以上字段,当然,实际项目中肯定不只是有这些字段,只是在配置上面配置文件中的sql语句时,把需要的字段查出来即可:
首先,在applicationContext.xml中配置数据库,设置datasource
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${druid.url}" />
<property name="username" value="${druid.username}" />
<property name="password" value="${druid.password}" />
<property name="maxActive" value="${druid.maxActive}" />
<property name="minIdle" value="${druid.minIdle}" />
<property name="maxWait" value="${druid.maxWait}" />
<property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}" />
<property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}" />
<property name="connectionProperties" value="config.decrypt=true" />
<property name="filters" value="config,stat,wall,log4j" />
bean>
然后在springmvc-security.xml中配置dataSource操作:
<security:authentication-manager alias="theAuthenticationManager">
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="dataSource" id="jdbcUserService"
users-by-username-query="select username,password,enabled from user where username = ?"
authorities-by-username-query="select username, authority from user where username = ?"
role-prefix="ROLE_"/>
<security:password-encoder ref="passwordEncoder">
<security:salt-source user-property="username"/>
security:password-encoder>
security:authentication-provider>
security:authentication-manager>
对于登陆成功后,我们很多情况需要对登陆后进行一些不同的业务逻辑处理,所以我们需要对登陆验证成功后的操作进行扩展,针对上面的配置,我们指定了一个跳转的链接,这样显然不合理,我们需要对登陆后进行一些扩展处理:
<security:form-login login-page="/user/loginPage.action"
authentication-failure-url="/common/failure.action"
login-processing-url="/user/j_spring_security_check"
default-target-url="/main/main.action" //如果不配置,就会返回到登陆前的页面
username-parameter="username" password-parameter="password"/>
修改default-target-url="",改为 authentication-success-handler-ref=””
<security:form-login login-page="/user/loginPage.action"
authentication-failure-url="/common/failure.action"
login-processing-url="/user/j_spring_security_check"
authentication-success-handler-ref="loginSuccessHandler"
username-parameter="username" password-parameter="password"/>
<bean id="loginSuccessHandler"
class="com.springsecurity.handler.LoginSuccessHandler">bean>
写一个登陆成功处理类:
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
//得到登录前的页面url
String prevUrl = "";
String URL = request.getHeader("Referer");
String args = request.getQueryString();
if (URL == null) {
prevUrl = "";
} else {
if (args != null) {
prevUrl = URL + "?" + args;
} else {
if (URL.contains("/user/loginPage")
|| URL.contains("/user/registePage")) {
prevUrl = "";
} else {
prevUrl = URL;
}
}
}
if (prevUrl == null || prevUrl.equals("")) {
prevUrl = "http://" + request.getServerName() + ":"
+ request.getServerPort()
+ request.getServletContext().getContextPath();
}
response.sendRedirect(prevUrl);
}
}
一,对springmvc-security.xml中进行配置:
<security:http use-expressions="true" access-denied-page="/WEB-INF/pages/common/noAuth.jsp">
<security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/common/loginPage.action"
authentication-failure-url="/common/failure.action"
default-target-url="/main/main.action"
username-parameter="username" password-parameter="password"/>
<security:logout logout-url="/securitylogout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/user/logout.action" />
<security:remember-me key="myspringsecurity" data-source-ref="dataSource"
token-validity-seconds="3600000" remember-me-parameter="rememberme" />
security:http>
<bean id="rememberMeAuthenticationFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
<constructor-arg index="0" ref="theAuthenticationManager"/>
<constructor-arg index="1" ref="rememberMeServices"/>
bean>
<bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices">
<constructor-arg index="0" value="myspringsecurity"/>
<constructor-arg index="1" ref="jdbcUserService"/>
<constructor-arg index="2" ref="tokenRepository"/>
bean>
<bean id="rememberMeAuthenticationProvider" class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
<constructor-arg value="myspringsecurity"/>
bean>
<bean id="tokenRepository" class="org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl">
<property name="createTableOnStartup" value="false"/>
<property name="dataSource" ref="dataSource"/>
bean>
需要建立一个表(persistent_logins),用来记录:
在进入登陆页面的时候,进行一些判断:
/**
* 前往登陆页面
* @return
*/
@RequestMapping("loginPage.action")
public String toLoginPage(){
//是不是记住密码
//并验证用户名和密码
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
if(RememberMeAuthenticationToken.class.isAssignableFrom(authentication.getClass())){
return "redirect:/main/main.action";
}
}
return "common/login";
}
在页面也可以验证是不是通过记住密码登陆的:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>successtitle>
head>
<body>
<sec:authorize access="isRememberMe()">
<h2># This user is login by "Remember Me Cookies".h2>
sec:authorize>
<sec:authorize access="isFullyAuthenticated()">
<h2># This user is login by username / password.h2>
sec:authorize>
<a href="${pageContext.request.contextPath }/securitylogout">退出a>
<div>
<div>${user.username}div>
<div>${msg}div>
<ul>
<li>消息消息息消息息消息息消息息消息息消息息消息<a href="${pageContext.request.contextPath}//main/delete.action">【删除】a>li>
<li>消息消息息消息息消息息消息息消息息消息息消息<a href="${pageContext.request.contextPath}//main/delete.action">【删除】a>li>
ul>
div>
body>
html>
如果一个用户用ROLE_ADMIN权限,那么他应该能够拥有ROLE_USER的权限,但是现在需要配置hasRole(‘ROLE_ADMIN’) or hasRole(‘ROLE_USER’)
或者在数据库中赋予两条权限的记录给用户同时赋予ROLE_ADMIN和ROLE_USER的权限,这样显然不合理:
所以我们需要定义权限的层级关系,比如ROLE_AMDIN > ROLE_USER
在springmvc-security.xml中配置<security:expression-handler ref=""/>
<security:http use-expressions="true" access-denied-page="/WEB-INF/pages/common/noAuth.jsp">
<security:intercept-url pattern="/user/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/common/loginPage.action"
authentication-failure-url="/common/failure.action"
default-target-url="/main/main.action"
username-parameter="username" password-parameter="password"/>
<security:logout logout-url="/securitylogout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/user/logout.action" />
<security:remember-me key="myspringsecurity" data-source-ref="dataSource"
token-validity-seconds="3600000" remember-me-parameter="rememberme" />
<security:session-management>
<security:concurrency-control error-if-maximum-exceeded="true" max-sessions="10"/>
security:session-management>
<security:intercept-url pattern="/main/delete.action" access="hasRole('ROLE_ADMIN')"/>
security:http>
<bean id="roleHierarchy" class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
<property name="hierarchy" value="ROLE_ADMIN > ROLE_USER"/>
bean>
<bean id="expressHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler">
<property name="roleHierarchy" ref="roleHierarchy"/>
bean>
现在我们的错误消息需要显示中文,此时,我们可以找到
spring-security-core-3.2.4.RELEASE.jar中的消息文件:
但是我们打开其中的messages_zh_CN.properties中的文件时,发现很多错误信息都太专业了,不适合做用户的交互提醒,所以我们可以将这个文件拷贝到我们项目中的properties/的配置文件包下面,并自定义其中的提醒。
并在springmvc-security.xml中配置:
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:properties/myMessage_zh_CN" />
bean>
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver" />
有时候对于某些需求我们需要自定义过滤器,并加入到security中,那么可以很简单的配置一个
<security:custom-filter ref="" after="LAST"/>
- FIRST
- CHANNEL_FILTER
- SECURITY_CONTEXT_FILTER
- CONCURRENT_SESSION_FILTER
- WEB_ASYNC_MANAGER_FILTER
- HEADERS_FILTER
- CSRF_FILTER
- LOGOUT_FILTER
- X509_FILTER
- PRE_AUTH_FILTER
- CAS_FILTER
- FORM_LOGIN_FILTER
- OPENID_FILTER
- LOGIN_PAGE_FILTER
- DIGEST_AUTH_FILTER
- BASIC_AUTH_FILTER
- REQUEST_CACHE_FILTER
- SERVLET_API_SUPPORT_FILTER
- JAAS_API_SUPPORT_FILTER
- REMEMBER_ME_FILTER
- ANONYMOUS_FILTER
- SESSION_MANAGEMENT_FILTER
- EXCEPTION_TRANSLATION_FILTER
- FILTER_SECURITY_INTERCEPTOR
- SWITCH_USER_FILTER
- LAST
对于tomcat如何配置https请参考:
http://jingyan.baidu.com/article/a948d6515d3e850a2dcd2ee6.html
对于spring security的默认对应关系是:http 80 https 443 ; http:8080 https:8443
如果需要自定义端口号的话,在
<security:port-mappings>
<security:port-mapping http="8089" https="8443"/>
security:port-mappings>
对于要使用访问的url:
<security:intercept-url pattern="/main/main.action" access="hasRole('ROLE_ADMIN')" requires-channel="https"/>