参考文档 : 自定义Login/Logout Filter、AuthenticationProvider、AuthenticationToken
Spring Security Reference
1. 需求:
在项目中需要用spring security来进行权限管理。并且需要对login的功能进行扩展。比如:登录成功以后,把用户名放入session中
2. 配置
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="Whale" version="3.1">
<display-name>Whaledisplay-name>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<async-supported>trueasync-supported>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>
classpath:META-INF/applicationContext.xml,
classpath:META-INF/applicationContext-security.xml
param-value>
context-param>
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListenerlistener-class>
listener>
<servlet>
<servlet-name>SpringMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:META-INF/spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
<async-supported>trueasync-supported>
servlet>
<servlet-mapping>
<servlet-name>SpringMVCservlet-name>
<url-pattern>/url-pattern>
servlet-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>
<welcome-file-list>
<welcome-file>/views/welcome.jspwelcome-file>
welcome-file-list>
<servlet-mapping>
<servlet-name>jspservlet-name>
<url-pattern>*.jspurl-pattern>
servlet-mapping>
<session-config>
<session-timeout>10session-timeout>
session-config>
web-app>
applicationContext-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-4.3.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="false">
<intercept-url pattern="/" access="permitAll" />
<intercept-url pattern="/admin**" access="hasRole('ADMIN')" />
<intercept-url pattern="/dba**" access="hasRole('DBA')" />
<form-login login-page="/views/login.jsp" username-parameter="username" password-parameter="password" authentication-failure-url="/views/accessDenied.jsp" />
<custom-filter before="FORM_LOGIN_FILTER" ref="customLoginFilter" />
<custom-filter before="LOGOUT_FILTER" ref="customLogoutFilter" />
http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="user" password="user" authorities="ROLE_USER" />
<user name="admin" password="root123" authorities="ROLE_ADMIN" />
<user name="dba" password="dba" authorities="ROLE_ADMIN,ROLE_DBA" />
user-service>
authentication-provider>
authentication-manager>
<beans:bean id="customLoginFilter" class="com.ninelephas.whale.springsecurity.CustomLoginFilter">
<beans:property name="authenticationManager" ref="authenticationManager" />
beans:bean>
<beans:bean id="customLogoutFilter" class="com.ninelephas.whale.springsecurity.CustomLogoutFilter">
<beans:property name="filterProcessesUrl" value="/logout" />
<beans:constructor-arg index="0" value="/" />
<beans:constructor-arg index="1">
<beans:array>
<beans:bean id="securityContextLogoutHandler" class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
<beans:bean id="customLogoutSuccessHandler" class="com.ninelephas.whale.springsecurity.CustomLogoutHandler" />
beans:array>
beans:constructor-arg>
beans:bean>
beans:beans>
/**
* @Title: CustomLoginFilter.java
* @Package com.ninelephas.whale.springsecurity
* @Description: TODO
* Copyright: Copyright (c) 2016
* Company:九象网络科技(上海)有限公司
*
* @author roamerxv
* @date 2016年9月6日 上午11:23:31
* @version V1.0.0
*/
package com.ninelephas.whale.springsecurity;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* @ClassName: CustomLoginFilter
* @Description: TODO
* @author Comsys-roamerxv
* @date 2016年9月6日 上午11:23:31
*
*/
public class CustomLoginFilter extends UsernamePasswordAuthenticationFilter {
/**
* Logger for this class
*/
private static final Logger logger = LogManager.getLogger(CustomLoginFilter.class.getName());
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
logger.debug("attemptAuthentication(HttpServletRequest, HttpServletResponse) - start"); //$NON-NLS-1$
String username = obtainUsername(request).toUpperCase().trim();
String password = obtainPassword(request);
Authentication returnAuthentication = null;
try {
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
returnAuthentication = this.getAuthenticationManager().authenticate(authRequest);
} catch (Exception e) {
logger.error(e);
throw e ;
}
logger.debug("attemptAuthentication(HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
return returnAuthentication;
}
@Override
protected void successfulAuthentication(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain,
Authentication authResult) throws IOException, ServletException {
logger.debug("successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication) - start"); //$NON-NLS-1$
super.successfulAuthentication(request, response, chain, authResult);
logger.debug("登录成功!");
logger.debug("successfulAuthentication(HttpServletRequest, HttpServletResponse, FilterChain, Authentication) - end"); //$NON-NLS-1$
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, AuthenticationException failed)
throws IOException, ServletException {
logger.debug("unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException) - start"); //$NON-NLS-1$
super.unsuccessfulAuthentication(request, response, failed);
logger.debug("登录失败!");
logger.debug("unsuccessfulAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationException) - end"); //$NON-NLS-1$
}
}
CustomLogoutFilter.java
/**
* @Title: CustomLogoutFilter.java
* @Package com.ninelephas.whale.springsecurity
* @Description: TODO
* Copyright: Copyright (c) 2016
* Company:九象网络科技(上海)有限公司
*
* @author roamerxv
* @date 2016年9月6日 下午3:13:07
* @version V1.0.0
*/
package com.ninelephas.whale.springsecurity;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
/**
* @ClassName: CustomLogoutFilter
* @Description: TODO
* @author Comsys-roamerxv
* @date 2016年9月6日 下午3:13:07
*
*/
public class CustomLogoutFilter extends LogoutFilter {
/**
* Logger for this class
*/
private static final Logger logger = LogManager.getLogger(CustomLogoutFilter.class.getName());
/**
*
* 创建一个新的实例 CustomLogoutFilter.
*
* Title:
*
*
* Description:
*
*
* @param logoutSuccessHandler
* @param handlers
*/
public CustomLogoutFilter(String logoutSuccessUrl, LogoutHandler... handlers) {
super(logoutSuccessUrl, handlers);
logger.debug("CustomLogoutFilter(String, LogoutHandler[]) - start"); //$NON-NLS-1$
logger.debug("CustomLogoutFilter(String, LogoutHandler[]) - end"); //$NON-NLS-1$
}
public CustomLogoutFilter(LogoutSuccessHandler logoutSuccessHandler, LogoutHandler... handlers) {
super(logoutSuccessHandler, handlers);
logger.debug("CustomLogoutFilter(LogoutSuccessHandler, LogoutHandler[]) - start"); //$NON-NLS-1$
logger.debug("CustomLogoutFilter(LogoutSuccessHandler, LogoutHandler[]) - end"); //$NON-NLS-1$
}
}
CustomLogoutHandler.java
/**
* @Title: CustomLogoutHandler.java
* @Package com.ninelephas.whale.springsecurity
* @Description: TODO
* Copyright: Copyright (c) 2016
* Company:九象网络科技(上海)有限公司
*
* @author roamerxv
* @date 2016年9月6日 下午3:38:30
* @version V1.0.0
*/
package com.ninelephas.whale.springsecurity;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
/**
* @ClassName: CustomLogoutHandler
* @Description: TODO
* @author Comsys-roamerxv
* @date 2016年9月6日 下午3:38:30
*
*/
public class CustomLogoutHandler implements LogoutHandler {
/**
* Logger for this class
*/
private static final Logger logger = LogManager.getLogger(CustomLogoutHandler.class.getName());
/**
* 创建一个新的实例 CustomLogoutHandler.
* Title:
* Description:
* @param logoutSuccessHandler
* @param handlers
*/
public CustomLogoutHandler() {
}
public void logout(HttpServletRequest request,HttpServletResponse response, Authentication authentication){
logger.debug("logout(HttpServletRequest, HttpServletResponse, Authentication) - start"); //$NON-NLS-1$
logger.debug("logout(HttpServletRequest, HttpServletResponse, Authentication) - end"); //$NON-NLS-1$
}
}