package com.www.common.security;
import com.www.common.enums.Constant;
import com.www.common.enums.RoleType;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.*;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.RedirectUrlBuilder;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 访问资源无权限时访问
* @Author: zhouchaoxi
* @Date: Created in 2018/7/7 0:13
* @Modified By:
*/
public class LoginEntryPoint implements AuthenticationEntryPoint,InitializingBean {
private PortMapper portMapper = new PortMapperImpl();
private PortResolver portResolver = new PortResolverImpl();
private String loginFormUrl;
private boolean forceHttps = false;
private boolean useForward = false;
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
public LoginEntryPoint(String loginFormUrl) {
Assert.notNull(loginFormUrl, "loginFormUrl cannot be null");
this.loginFormUrl = loginFormUrl;
}
/**
* Performs the redirect (or forward) to the login form URL.
*/
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
String redirectUrl = null;
String returnUrl = buildHttpReturnUrlForRequest(request);
System.out.println("========"+returnUrl+"========");
if (returnUrl.contains("/admin/")){
request.getSession().setAttribute(Constant.LOGIN_ROLE, RoleType.ADMIN());
this.loginFormUrl="/admin/login.do";
}else{
request.getSession().setAttribute(Constant.LOGIN_ROLE, RoleType.USER());
}
if (useForward) {
if (forceHttps && "http".equals(request.getScheme())) {
redirectUrl = buildHttpsRedirectUrlForRequest(request);
}
if (redirectUrl == null) {
String loginForm = determineUrlToUseForThisRequest(request, response, authException);
RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);
dispatcher.forward(request, response);
return;
}
} else {
redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);
}
redirectStrategy.sendRedirect(request, response, redirectUrl);
}
protected String buildHttpReturnUrlForRequest(HttpServletRequest request) throws IOException, ServletException {
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setScheme("http");
urlBuilder.setServerName(request.getServerName());
urlBuilder.setPort(request.getServerPort());
urlBuilder.setContextPath(request.getContextPath());
urlBuilder.setServletPath(request.getServletPath());
urlBuilder.setPathInfo(request.getPathInfo());
urlBuilder.setQuery(request.getQueryString());
return urlBuilder.getUrl();
}
public void afterPropertiesSet() throws Exception {
Assert.isTrue(StringUtils.hasText(loginFormUrl) && UrlUtils.isValidRedirectUrl(loginFormUrl),
"loginFormUrl must be specified and must be a valid redirect URL");
if (useForward && UrlUtils.isAbsoluteUrl(loginFormUrl)) {
throw new IllegalArgumentException("useForward must be false if using an absolute loginFormURL");
}
Assert.notNull(portMapper, "portMapper must be specified");
Assert.notNull(portResolver, "portResolver must be specified");
}
/**
* Allows subclasses to modify the login form URL that should be applicable for a
* given request.
*
* @param request the request
* @param response the response
* @param exception the exception
* @return the URL (cannot be null or empty; defaults to {@link #getLoginFormUrl()})
*/
protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
return getLoginFormUrl();
}
protected String buildRedirectUrlToLoginPage(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
String loginForm = determineUrlToUseForThisRequest(request, response, authException);
if (UrlUtils.isAbsoluteUrl(loginForm)) {
return loginForm;
}
int serverPort = portResolver.getServerPort(request);
String scheme = request.getScheme();
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setScheme(scheme);
urlBuilder.setServerName(request.getServerName());
urlBuilder.setPort(serverPort);
urlBuilder.setContextPath(request.getContextPath());
urlBuilder.setPathInfo(loginForm);
if (forceHttps && "http".equals(scheme)) {
Integer httpsPort = portMapper.lookupHttpsPort(Integer.valueOf(serverPort));
if (httpsPort != null) {
// Overwrite scheme and port in the redirect URL
urlBuilder.setScheme("https");
urlBuilder.setPort(httpsPort.intValue());
}
else {
}
}
return urlBuilder.getUrl();
}
/**
* Builds a URL to redirect the supplied request to HTTPS. Used to redirect the
* current request to HTTPS, before doing a forward to the login page.
*/
protected String buildHttpsRedirectUrlForRequest(HttpServletRequest request) throws IOException, ServletException {
int serverPort = portResolver.getServerPort(request);
Integer httpsPort = portMapper.lookupHttpsPort(Integer.valueOf(serverPort));
if (httpsPort != null) {
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setScheme("https");
urlBuilder.setServerName(request.getServerName());
urlBuilder.setPort(httpsPort.intValue());
urlBuilder.setContextPath(request.getContextPath());
urlBuilder.setServletPath(request.getServletPath());
urlBuilder.setPathInfo(request.getPathInfo());
urlBuilder.setQuery(request.getQueryString());
return urlBuilder.getUrl();
}
return null;
}
/**
* Set to true to force login form access to be via https. If this value is true (the
* default is false), and the incoming request for the protected resource which
* triggered the interceptor was not already https, then the client will
* first be redirected to an https URL, even if serverSideRedirect is set to
* true.
*/
public void setForceHttps(boolean forceHttps) {
this.forceHttps = forceHttps;
}
protected boolean isForceHttps() {
return forceHttps;
}
public String getLoginFormUrl() {
return loginFormUrl;
}
public void setPortMapper(PortMapper portMapper) {
Assert.notNull(portMapper, "portMapper cannot be null");
this.portMapper = portMapper;
}
protected PortMapper getPortMapper() {
return portMapper;
}
public void setPortResolver(PortResolver portResolver) {
Assert.notNull(portResolver, "portResolver cannot be null");
this.portResolver = portResolver;
}
protected PortResolver getPortResolver() {
return portResolver;
}
/**
* Tells if we are to do a forward to the {@code loginFormUrl} using the
* {@code RequestDispatcher}, instead of a 302 redirect.
*
* @param useForward true if a forward to the login page should be used. Must be false
* (the default) if {@code loginFormUrl} is set to an absolute value.
*/
public void setUseForward(boolean useForward) {
this.useForward = useForward;
}
protected boolean isUseForward() {
return useForward;
}
}
package com.www.common.security;
import com.www.common.enums.Constant;
import com.www.common.utils.Const;
import org.springframework.security.authentication.AuthenticationServiceException;
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;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @描述:
* @作者: zhouChaoXi
* @时间: 2018/7/3 21:20
*/
public class LoginFromFilter extends UsernamePasswordAuthenticationFilter{
public static final String SPRING_SECURITY_FORM_VALID_CODE = "code";
private String codeParameter = SPRING_SECURITY_FORM_VALID_CODE;
public LoginFromFilter() {
super();
}
/**
* 如果是通过页面进来验证码效验
* 非页面进入不效验
* 并拼接用户名和登录角色
* @Author: zhouchaoxi
* @Date: Created in 2018/8/4 17:44
* @Modified By:
*/
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
String code = (String)request.getSession().getAttribute(Constant.CODE);
String inputCode = obtainValidCode(request);
String login_role=request.getParameter(Constant.LOGIN_ROLE);
request.getSession().setAttribute(Constant.LOGIN_ROLE,login_role);
String username=obtainUsername(request);
String password=obtainPassword(request);
if (username == null)username = "";
if (password == null)password = "";
username=username+"__"+login_role;
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
if (code==null){
return super.getAuthenticationManager().authenticate(authRequest);
}else if(code.toUpperCase().equals(inputCode.toUpperCase())){
return super.getAuthenticationManager().authenticate(authRequest);
}else{
throw new AuthenticationServiceException("验证码输入错误");
}
}
protected String obtainValidCode(HttpServletRequest request) {
return request.getParameter(codeParameter);
}
public String getCodeParameter() {
return codeParameter;
}
public void setCodeParameter(String codeParameter) {
Assert.hasText(codeParameter, "Valid code parameter must not be empty or null");
this.codeParameter = codeParameter;
}
}
package com.www.common.security;
import com.www.common.enums.RoleType;
import com.www.common.pojo.User;
import com.www.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* 从数据库中读入用户的密码
* 角色信息,是否锁定,账号是否过期等
* @author
*/
public class MyUserDetailService implements UserDetailsService {
@Autowired
private UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String[] usernameList=username.split("__");
String userName="";
String login_role= RoleType.USER();
if (usernameList.length>1){
for(int i=0;i auths = new ArrayList();
// String roles=user.getUserRole();
// if (!CommUtil.isNull(roles)){
// String[] role=roles.split(",");
// for (String auth:role){
// auths.add(new SimpleGrantedAuthority(auth));
// }
// }
// User userDetails = new User(username, user.getPassword(), true, true, true, true, auths);
return user;
}
throw new UsernameNotFoundException("UserName " + username + " not found");
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml&q
Mockito单元测试实例:
public class SettingServiceTest {
private List<PersonDTO> personList = new ArrayList<PersonDTO>();
@InjectMocks
private SettingPojoService settin
public class DeleteExtraSpace {
/**
* 题目:给定字符串,删除开始和结尾处的空格,并将中间的多个连续的空格合并成一个。
* 方法1.用已有的String类的trim和replaceAll方法
* 方法2.全部用正则表达式,这个我不熟
* 方法3.“重新发明轮子”,从头遍历一次
*/
public static v
今天早上打开MyEclipse时,自动关闭!弹出An error has occurred.See the log file错误提示!
很郁闷昨天启动和关闭还好着!!!打开几次依然报此错误,确定不是眼花了!
打开日志文件!找到当日错误文件内容:
--------------------------------------------------------------------------