核心思想:就是重写从request中获取用户名,密码的方法
直接上代码。
参考资料:
http://docs.spring.io/spring-security/site/docs/4.0.3.RELEASE/reference/htmlsingle/#preface
直接上代码。
application-security.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" 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.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<security:http pattern="/login/**" security="none">security:http>
<security:http auto-config="false" use-expressions="true" entry-point-ref="http403EntryPoint">
<security:csrf disabled="true" />
<security:headers>
<security:frame-options policy="SAMEORIGIN" />
<security:cache-control disabled="true" />
<security:content-type-options disabled="true" />
security:headers>
<security:logout invalidate-session="true" logout-url="/login/logout.do" logout-success-url="/login/outSuccess.do"
delete-cookies="true" />
<security:session-management invalid-session-url="/login/timedout.do" session-fixation-protection="none"
session-authentication-error-url="/login/timedout.do">
<security:concurrency-control error-if-maximum-exceeded="false" expired-url="/login/timedout.do"
max-sessions="1" />
security:session-management>
<security:custom-filter ref="mySecurityFilter" before="FILTER_SECURITY_INTERCEPTOR" />
<security:custom-filter ref="CustomUsernamePasswordAuthenticationFilter" before="FORM_LOGIN_FILTER" />
security:http>
<bean id="CustomUsernamePasswordAuthenticationFilter" class="u.frame.web.trade.security.MyUsernamePasswordAuthenticationFilter">
<property name="authenticationManager" ref="authenticationManager" />
<property name="authenticationSuccessHandler" ref="successHandler" />
<property name="authenticationFailureHandler" ref="failureHandler" />
<property name="filterProcessesUrl" value="/logincheck.do" />
bean>
<bean id="mySecurityFilter" class="u.frame.web.trade.security.MyFilterSecurityInterceptor" />
<bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
<constructor-arg>
<list>
<ref bean="daoAuthenticationProvider" />
list>
constructor-arg>
bean>
<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
<property name="userDetailsService" ref="userServiceDetail" />
<property name="passwordEncoder" ref="standardPasswordEncoder" />
<property name="hideUserNotFoundExceptions" value="false" />
bean>
<bean id="successHandler" class="u.frame.web.trade.security.MySimpleUrlAuthenticationSuccessHandler">
<property name="defaultTargetUrl" value="/login/success.do" />
bean>
<bean id="failureHandler" class="u.frame.web.trade.security.MySimpleUrlAuthenticationFailureHandler">
<property name="defaultFailureUrl" value="/login/error.do" />
bean>
<bean id="http403EntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
<bean id="userServiceDetail" class="u.frame.web.trade.security.MyUserDetailServiceImpl" />
<bean id="standardPasswordEncoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder">
<constructor-arg value="q1w2e3r4t5y6u7i8o9p0" />
bean>
beans>
MyUsernamePasswordAuthenticationFilter.java
package u.frame.web.trade.security;
import java.io.BufferedReader;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import u.frame.web.trade.model.Login;
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
static Log log = LogFactory.getLog(MyUsernamePasswordAuthenticationFilter.class);
// 用户的登录信息
private Login login;
@Override
protected String obtainPassword(HttpServletRequest request) {
System.out.println("MyUsernamePasswordAuthenticationFilter-obtainPassword");
if (checkJson(request)) {
if (login != null) {
return login.getPassWord();
}
}
return super.obtainPassword(request);
}
@Override
protected String obtainUsername(HttpServletRequest request) {
System.out.println("MyUsernamePasswordAuthenticationFilter-obtainUsername");
if (checkJson(request)) {
if (login != null) {
return login.getUserName();
}
}
return super.obtainUsername(request);
}
public boolean checkJson(HttpServletRequest request) {
try {
if ("application/json".equals(request.getHeader("Content-Type"))) {
StringBuffer sb = new StringBuffer();
String line = null;
BufferedReader reader;
reader = request.getReader();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
if (StringUtils.isNotEmpty(sb.toString())) {
ObjectMapper mapper = new ObjectMapper();
login = mapper.readValue(sb.toString(), Login.class);
}
return true;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
MyFilterSecurityInterceptor.java
package u.frame.web.trade.security;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import u.frame.util.ResponseJsonUtil;
/**
*/
public class MyFilterSecurityInterceptor implements Filter {
static final Logger logger = LogManager.getLogger(MyFilterSecurityInterceptor.class.getName());
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest myrequest = (HttpServletRequest) request;
if (myrequest.getSession().getAttribute("loginUser") == null) {
ResponseJsonUtil.jsonResponse(response, "F0001");
} else {
chain.doFilter(request, response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
MySimpleUrlAuthenticationSuccessHandler.java
package u.frame.web.trade.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import u.frame.common.Result;
import u.frame.util.ResponseJsonUtil;
public class MySimpleUrlAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
static Log log = LogFactory.getLog(MySimpleUrlAuthenticationSuccessHandler.class);
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
if ("application/json".equals(request.getHeader("Content-Type"))) {
ResponseJsonUtil.jsonResponse(response, new Result<>());
} else {
super.onAuthenticationSuccess(request, response, auth);
}
}
}
MySimpleUrlAuthenticationFailureHandler.java
package u.frame.web.trade.security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import u.frame.util.ResponseJsonUtil;
public class MySimpleUrlAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
static Log log = LogFactory.getLog(MySimpleUrlAuthenticationFailureHandler.class);
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
if ("application/json".equals(request.getHeader("Content-Type"))) {
ResponseJsonUtil.jsonResponse(response, exception.getMessage());
} else {
// TODO Auto-generated method stub
super.onAuthenticationFailure(request, response, exception);
}
}
}
MyUserDetailServiceImpl.java
package u.frame.web.trade.security;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import u.frame.web.trade.model.SysOperator;
import u.frame.web.trade.service.SysOperatorSer;
/**
* @description 项目实现的用户查询服务,将用户信息查询出来(用于实现用户的认证)
*/
public class MyUserDetailServiceImpl implements UserDetailsService {
static final Logger logger = LogManager.getLogger(MyUserDetailServiceImpl.class.getName());
@Autowired
private SysOperatorSer sysOperatorSer;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("MyUserDetailServiceImpl" + username);
if (StringUtils.isEmpty(username)) {
// 用户名为空
throw new UsernameNotFoundException("F0005");
}
SysOperator sysOperator = obtainByUsername(username);
if (sysOperator == null) {
// 没有此用户
throw new UsernameNotFoundException("F0003");
}
boolean enabled = true; // 可用性 :true:可用 false:不可用
boolean accountNonExpired = true; // 过期性 :true:没过期 false:过期
boolean credentialsNonExpired = true; // 有效性 :true:凭证有效 false:凭证无效
boolean accountNonLocked = true; // 锁定性 :true:未锁定 false:已锁定
Set authorities = new HashSet();
return new org.springframework.security.core.userdetails.User(//
sysOperator.getLoginCode(), //
// user.getUserPassword()+"{"+user.getUserName()+"}",
sysOperator.getLoginPwd(), //
enabled, //
accountNonExpired, //
credentialsNonExpired, //
accountNonLocked, //
authorities//
);
}
public SysOperator obtainByUsername(String username) {
if (StringUtils.isEmpty(username)) {
return null;
}
SysOperator sysOperator = new SysOperator();
sysOperator.setLoginCode(username);
List list = sysOperatorSer.getList(sysOperator);
if (CollectionUtils.isEmpty(list) || list.size() != 1) {
// 没有此用户
return null;
}
sysOperator = list.get(0);
return sysOperator;
}
}