Commit 028c9c76 by PWF-WK01\pengwufeng

场站用户登录

parent 128c0dee
...@@ -52,9 +52,13 @@ import com.beecode.inz.authentication.handler.RESTAppAuthenticationSuccessHandle ...@@ -52,9 +52,13 @@ import com.beecode.inz.authentication.handler.RESTAppAuthenticationSuccessHandle
import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint; import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint;
import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler; import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler;
import com.beecode.inz.authentication.handler.RESTAuthenticationSuccessHandler; import com.beecode.inz.authentication.handler.RESTAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTWarehouseUserAuthenticationSuccessHandler;
import com.beecode.inz.authentication.provider.AppUserAuthenticationProvider; import com.beecode.inz.authentication.provider.AppUserAuthenticationProvider;
import com.beecode.inz.authentication.provider.UserAuthenticationProvider; import com.beecode.inz.authentication.provider.UserAuthenticationProvider;
import com.beecode.inz.authentication.provider.WarehouseUserAuthenticationProvider;
import com.beecode.inz.basis.context.customer.CustomerContextRepository; import com.beecode.inz.basis.context.customer.CustomerContextRepository;
import com.beecode.inz.basis.context.warehouse.WarehouseUserContextPersistenceFilter;
import com.beecode.inz.basis.context.warehouse.WarehouseUserContextRepository;
/** /**
* @author Joe Grandja * @author Joe Grandja
...@@ -104,6 +108,14 @@ public class SecurityConfig { ...@@ -104,6 +108,14 @@ public class SecurityConfig {
@Autowired @Autowired
private UserAuthenticationProvider userAuthenticationProvider; private UserAuthenticationProvider userAuthenticationProvider;
@Autowired
private RESTWarehouseUserAuthenticationSuccessHandler warehouseUserAuthenticationSuccessHandler;
@Autowired
private WarehouseUserAuthenticationProvider warehouseUserAuthenticationProvider;
@Autowired
private WarehouseUserContextRepository warehouseUserContextRepository;
@Autowired @Autowired
private RestLogoutHandler CLogoutHandler; private RestLogoutHandler CLogoutHandler;
...@@ -126,10 +138,7 @@ public class SecurityConfig { ...@@ -126,10 +138,7 @@ public class SecurityConfig {
@Autowired @Autowired
private AminoContextRepository repository; private AminoContextRepository repository;
@Autowired
private CustomerContextRepository customerContextRepository;
@Configuration @Configuration
@Order(1) @Order(1)
public class InzAppSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { public class InzAppSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
...@@ -176,7 +185,86 @@ public class SecurityConfig { ...@@ -176,7 +185,86 @@ public class SecurityConfig {
} }
@Configuration @Configuration
@Order(2)
public class WarehouseUserSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
List<SessionAuthenticationStrategy> delegateStrategies = new ArrayList<SessionAuthenticationStrategy>();
delegateStrategies.add(concurrentSessionControlAuthenticationStrategy);
http.sessionManagement().maximumSessions(1);
http.csrf().disable();
http.cors().disable();
http.antMatcher("/warehouse/user/login").authorizeRequests().anyRequest().authenticated();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
InzWebAuthenticationFilter filter = new InzWebAuthenticationFilter();
filter.setAuthenticationSuccessHandler(warehouseUserAuthenticationSuccessHandler);
filter.setAuthenticationFailureHandler(authenticationFailureHandler);
filter.setAuthenticationManager(authenticationManager());
filter.setSessionAuthenticationStrategy(new CompositeSessionAuthenticationStrategy(delegateStrategies));
RequestMatcher requestMatcher = new AntPathRequestMatcher("/warehouse/user/login", "POST");
filter.setRequiresAuthenticationRequestMatcher(requestMatcher);
http.addFilterAt(filter, UsernamePasswordAuthenticationFilter.class);
InzConcurrentSessionFilter inzConcurrentSessionFilter = new InzConcurrentSessionFilter(sessionRegistry) ;
http.addFilterAt(inzConcurrentSessionFilter, ConcurrentSessionFilter.class);
WarehouseUserContextPersistenceFilter contextPersistenceFilter = new WarehouseUserContextPersistenceFilter(metadataRuntime, warehouseUserContextRepository);
http.addFilterAfter(contextPersistenceFilter, SecurityContextPersistenceFilter.class);
http.addFilterAfter(new INZTenantAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(warehouseUserAuthenticationProvider);
}
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
@Configuration
@Order(3) @Order(3)
public class WarehouseApiConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
List<SessionAuthenticationStrategy> delegateStrategies = new ArrayList<SessionAuthenticationStrategy>();
delegateStrategies.add(concurrentSessionControlAuthenticationStrategy);
http.sessionManagement().maximumSessions(1);
http.csrf().disable();
http.cors().disable();
http.antMatcher("/warehouse/**").authorizeRequests().anyRequest().authenticated();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
InzConcurrentSessionFilter inzConcurrentSessionFilter = new InzConcurrentSessionFilter(sessionRegistry) ;
http.addFilterAt(inzConcurrentSessionFilter, ConcurrentSessionFilter.class);
WarehouseUserContextPersistenceFilter contextPersistenceFilter = new WarehouseUserContextPersistenceFilter(metadataRuntime, warehouseUserContextRepository);
http.addFilterAfter(contextPersistenceFilter, SecurityContextPersistenceFilter.class);
http.addFilterAfter(new INZTenantAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
http.logout().logoutUrl("/logout")
.addLogoutHandler(logoutHandler).invalidateHttpSession(true)
.permitAll();
}
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}
}
@Configuration
@Order(4)
public class WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { public class WebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
......
...@@ -19,9 +19,11 @@ import com.beecode.inz.authentication.handler.RESTAppAuthenticationSuccessHandle ...@@ -19,9 +19,11 @@ import com.beecode.inz.authentication.handler.RESTAppAuthenticationSuccessHandle
import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint; import com.beecode.inz.authentication.handler.RESTAuthenticationEntryPoint;
import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler; import com.beecode.inz.authentication.handler.RESTAuthenticationFailureHandler;
import com.beecode.inz.authentication.handler.RESTAuthenticationSuccessHandler; import com.beecode.inz.authentication.handler.RESTAuthenticationSuccessHandler;
import com.beecode.inz.authentication.handler.RESTWarehouseUserAuthenticationSuccessHandler;
import com.beecode.inz.authentication.internal.service.SMSsendingCustomerServiceImpl; import com.beecode.inz.authentication.internal.service.SMSsendingCustomerServiceImpl;
import com.beecode.inz.authentication.internal.service.SMSsendingServiceImpl; import com.beecode.inz.authentication.internal.service.SMSsendingServiceImpl;
import com.beecode.inz.authentication.provider.AppUserAuthenticationProvider; import com.beecode.inz.authentication.provider.AppUserAuthenticationProvider;
import com.beecode.inz.authentication.provider.WarehouseUserAuthenticationProvider;
import com.beecode.inz.authentication.service.SMSsendingCustomerService; import com.beecode.inz.authentication.service.SMSsendingCustomerService;
import com.beecode.inz.authentication.service.SMSsendingService; import com.beecode.inz.authentication.service.SMSsendingService;
import com.beecode.inz.authentication.session.InzConcurrentSessionControlAuthenticationStrategy; import com.beecode.inz.authentication.session.InzConcurrentSessionControlAuthenticationStrategy;
...@@ -68,6 +70,11 @@ public class AuthenticationConfiguration { ...@@ -68,6 +70,11 @@ public class AuthenticationConfiguration {
return new RESTAppAuthenticationSuccessHandler(); return new RESTAppAuthenticationSuccessHandler();
} }
@Bean
public RESTWarehouseUserAuthenticationSuccessHandler warehouseUserAuthenticationSuccessHandler() {
return new RESTWarehouseUserAuthenticationSuccessHandler();
}
@Bean("com.beecode.inz.authentication.config.RedisConfiguration.redisTemplate") @Bean("com.beecode.inz.authentication.config.RedisConfiguration.redisTemplate")
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) { public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate< String, String> redisTemplate = new RedisTemplate<String,String>(); RedisTemplate< String, String> redisTemplate = new RedisTemplate<String,String>();
...@@ -110,4 +117,9 @@ public class AuthenticationConfiguration { ...@@ -110,4 +117,9 @@ public class AuthenticationConfiguration {
return new AppUserAuthenticationProvider(); return new AppUserAuthenticationProvider();
} }
@Bean
public WarehouseUserAuthenticationProvider warehouseUserAuthenticationProvider() {
return new WarehouseUserAuthenticationProvider();
}
} }
...@@ -55,8 +55,7 @@ public class InzWebAuthenticationFilter extends AbstractAuthenticationProcessing ...@@ -55,8 +55,7 @@ public class InzWebAuthenticationFilter extends AbstractAuthenticationProcessing
username = username.trim(); username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken( UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
username, password);
// Allow subclasses to set the "details" property // Allow subclasses to set the "details" property
setDetails(request, authRequest); setDetails(request, authRequest);
......
package com.beecode.inz.authentication.handler;
import java.io.IOException;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.beecode.inz.authentication.constants.AuthcConstants;
import com.beecode.inz.authentication.constants.LoginLogConstants;
import com.beecode.inz.authentication.constants.TenantUserConstants;
import com.beecode.inz.authentication.datamodel.LoginLog;
import com.beecode.inz.authentication.enumeration.LoginModeEnum;
import com.beecode.inz.authentication.enumeration.LoginStateEnum;
import com.beecode.inz.authentication.enumeration.LoginTerminalEnum;
import com.beecode.inz.authentication.service.LoginLogService;
import com.beecode.inz.authentication.util.LoginLogUtil;
import com.beecode.inz.basis.pojo.WarehouseUser;
/**
* 处理砂厂用户登录成功后的返回
*
* @author pengwufeng
*
*/
@Component
public class RESTWarehouseUserAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
@Autowired
private LoginLogService loginLogService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
clearAuthenticationAttributes(request);
LoginLog loginLog = getLoginLog(request);
try {
String tenant = request.getParameter(AuthcConstants.TENANT);
WarehouseUser warehouseUser = (WarehouseUser) authentication.getPrincipal();
if (warehouseUser != null) {
JSONObject returnJson = new JSONObject();
request.getSession().setAttribute(AuthcConstants.SESSION_TENANTID, tenant);
request.getSession().setAttribute(AuthcConstants.USERID, warehouseUser.getId());
request.getSession().setAttribute(AuthcConstants.USERNAME, warehouseUser.getUsername());
request.getSession().setAttribute(AuthcConstants.TELEPHONE, warehouseUser.getTelephone());
request.getSession().setAttribute("mobile", true);
request.getSession().setMaxInactiveInterval(30 * 24 * 60 * 60);
loginLog.setTenantId(tenant);
loginLog.setDescription("warehouseUser login");
loginLogService.insert(loginLog);
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
returnJson.put(AuthcConstants.USERID, warehouseUser.getId());
returnJson.put(AuthcConstants.USERNAME, warehouseUser.getUsername());
returnJson.put(AuthcConstants.TELEPHONE, warehouseUser.getTelephone());
returnJson.put(AuthcConstants.MESSAGE, "success");
returnJson.put(AuthcConstants.TOKEN, attr.getSessionId());
returnJson.put(AuthcConstants.TENANT, tenant);
response.getWriter().append(returnJson.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public LoginLog getLoginLog(HttpServletRequest request) {
LoginLog loginLog = new LoginLog();
String userAgent = request.getHeader(LoginLogConstants.USER_AGENT);
if (userAgent.contains(LoginLogConstants.WINDOWS)) {
loginLog.setLoginTerminal(LoginTerminalEnum.WEB.getValue());
} else if (userAgent.contains(LoginLogConstants.ANDROID)) {
loginLog.setLoginTerminal(LoginTerminalEnum.ANDROID.getValue());
} else if (userAgent.contains(LoginLogConstants.IOS)) {
loginLog.setLoginTerminal(LoginTerminalEnum.ISO.getValue());
} else {
loginLog.setLoginTerminal(LoginTerminalEnum.WEB.getValue());
}
loginLog.setAccountNumber(request.getParameter(TenantUserConstants.USERNAME));
loginLog.setLoginMode(request.getParameter(TenantUserConstants.USERNAME) == null
? LoginModeEnum.QRCODELODIN.getValue() : LoginModeEnum.USERNAMEPASSWORD.getValue());
loginLog.setIp(LoginLogUtil.getClientIp(request));
loginLog.setLoginTime(new Date());
loginLog.setLoginState(LoginStateEnum.SUCCESS.getValue());
return loginLog;
}
}
package com.beecode.inz.authentication.provider;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.beecode.inz.basis.pojo.WarehouseUser;
import com.beecode.inz.basis.service.WarehouseUserService;
/**
* 砂厂用户验证器
* @author pengwufeng
*
*/
public class WarehouseUserAuthenticationProvider implements AuthenticationProvider {
@Autowired
WarehouseUserService warehouseUserService;
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String passWord = (String) authentication.getCredentials();
WarehouseUser warehouseUser = warehouseUserService.getByUsername(username);
if(null == warehouseUser) {
throw new BadCredentialsException("用户名或密码错误!");
}
String pwd = warehouseUser.getPassword();
if (!passwordEncoder.matches(passWord, pwd)) {
throw new BadCredentialsException("用户名或密码错误!");
}
List<SimpleGrantedAuthority> roleList = new ArrayList<SimpleGrantedAuthority>();
return new UsernamePasswordAuthenticationToken(warehouseUser, passWord, roleList);
}
@Override
public boolean supports(Class<?> authentication) {
return authentication != null && authentication == UsernamePasswordAuthenticationToken.class;
}
}
...@@ -5,13 +5,20 @@ import org.springframework.context.annotation.Configuration; ...@@ -5,13 +5,20 @@ import org.springframework.context.annotation.Configuration;
import com.beecode.inz.basis.context.customer.CustomerContextRepository; import com.beecode.inz.basis.context.customer.CustomerContextRepository;
import com.beecode.inz.basis.context.customer.HttpSessionCustomerContextRepository; import com.beecode.inz.basis.context.customer.HttpSessionCustomerContextRepository;
import com.beecode.inz.basis.context.warehouse.HttpSessionWarehouseUserContextRepository;
import com.beecode.inz.basis.context.warehouse.WarehouseUserContextRepository;
@Configuration @Configuration
public class CustomerContextConfiguration { public class ContextConfiguration {
@Bean @Bean
public CustomerContextRepository customerContextRepository() { public CustomerContextRepository customerContextRepository() {
return new HttpSessionCustomerContextRepository(); return new HttpSessionCustomerContextRepository();
} }
@Bean
public WarehouseUserContextRepository warehouseUserContextRepository() {
return new HttpSessionWarehouseUserContextRepository();
}
} }
...@@ -95,7 +95,7 @@ public class HttpSessionCustomerContextRepository implements CustomerContextRepo ...@@ -95,7 +95,7 @@ public class HttpSessionCustomerContextRepository implements CustomerContextRepo
Customer customer = null; Customer customer = null;
String customerObj = (String)httpSession.getAttribute(CustomerContextConstants.CURRENT_CUSTOMER); String customerObj = (String)httpSession.getAttribute(CustomerContextConstants.CURRENT_CUSTOMER);
if (StringUtils.isEmpty(customer)) { if (StringUtils.isEmpty(customerObj)) {
try { try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(null == authentication) { if(null == authentication) {
......
package com.beecode.inz.basis.context.warehouse;
import javax.servlet.AsyncContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.security.web.util.OnCommittedResponseWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
import com.beecode.inz.basis.exception.NotFoundWarehouseUserException;
import com.beecode.inz.basis.pojo.WarehouseUser;
import com.beecode.inz.basis.service.WarehouseUserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HttpSessionWarehouseUserContextRepository implements WarehouseUserContextRepository {
@Autowired
private WarehouseUserService warehouseUserService;
@Autowired
private ObjectMapper objectMapper;
public static final String WAREHOUSE_USER_CONTEXT_KEY = "WAREHOUSE_USER_CONTEXT";
protected final Log logger = LogFactory.getLog(this.getClass());
private final Object contextObject = WarehouseUserContextHolder.createEmptyContext();
private boolean isServlet3 = ClassUtils.hasMethod(ServletRequest.class, "startAsync");
private AuthenticationTrustResolver trustResolver = new AuthenticationTrustResolverImpl();
@Override
@Transactional(readOnly=true)
public WarehouseUserContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
HttpServletRequest request = requestResponseHolder.getRequest();
HttpServletResponse response = requestResponseHolder.getResponse();
HttpSession httpSession = request.getSession(false);
WarehouseUserContext context = generateNewContext(httpSession);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && !trustResolver.isAnonymous(authentication)) {
WarehouseUserContextImpl contextImpl = (WarehouseUserContextImpl)context;
if(contextImpl.getWarehouseUser() == null) {
loadContext(httpSession, contextImpl);
}
}
SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper(response, request, httpSession != null, context);
requestResponseHolder.setResponse(wrappedResponse);
if (isServlet3) {
requestResponseHolder.setRequest(new Servlet3SaveToSessionRequestWrapper(request, wrappedResponse));
}
return context;
}
@Override
public boolean containsContext(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return false;
}
return session.getAttribute(WAREHOUSE_USER_CONTEXT_KEY) != null;
}
protected WarehouseUserContext generateNewContext(HttpSession httpSession) {
return WarehouseUserContextHolder.createEmptyContext();
}
/**
* 获取当前用户context
* @throws Exception
*/
private void loadContext(HttpSession httpSession, WarehouseUserContextImpl contextImpl) {
if (null == httpSession) {
return;
}
WarehouseUser warehouseUser = null;
String warehouseUserJsonObj = (String)httpSession.getAttribute(WarehouseUserContextConstants.CURRENT_WAREHOUSE_USER);
if (StringUtils.isEmpty(warehouseUserJsonObj)) {
try {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(null == authentication) {
return;
}
String userName = authentication.getName();
if(StringUtils.isEmpty(userName)) {
return;
}
warehouseUser = warehouseUserService.getByUsername(userName);
if(null == warehouseUser) {
throw new NotFoundWarehouseUserException("not found warehouseUser#" + userName);
}
httpSession.setAttribute(WarehouseUserContextConstants.CURRENT_WAREHOUSE_USER, objectMapper.writeValueAsString(warehouseUser));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
} else if (warehouseUserJsonObj instanceof String) {
try {
warehouseUser = objectMapper.readValue(warehouseUserJsonObj, WarehouseUser.class);
}catch(Exception e) {
e.printStackTrace();
httpSession.removeAttribute(WarehouseUserContextConstants.CURRENT_WAREHOUSE_USER);
}
}
contextImpl.setWarehouseUser(warehouseUser);
}
//~ Inner Classes ==================================================================================================
private static class Servlet3SaveToSessionRequestWrapper extends HttpServletRequestWrapper {
private final SaveToSessionResponseWrapper response;
public Servlet3SaveToSessionRequestWrapper(HttpServletRequest request, SaveToSessionResponseWrapper response) {
super(request);
this.response = response;
}
@Override
public AsyncContext startAsync() {
response.disableSaveOnResponseCommitted();
return super.startAsync();
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse)
throws IllegalStateException {
response.disableSaveOnResponseCommitted();
return super.startAsync(servletRequest, servletResponse);
}
}
final class SaveToSessionResponseWrapper extends OnCommittedResponseWrapper {
private final HttpServletRequest request;
private final boolean httpSessionExistedAtStartOfRequest;
public SaveToSessionResponseWrapper(HttpServletResponse response, HttpServletRequest request,
boolean httpSessionExistedAtStartOfRequest, WarehouseUserContext context) {
super(response);
this.request = request;
this.httpSessionExistedAtStartOfRequest = httpSessionExistedAtStartOfRequest;
// this.contextBeforeExecution = context;
// this.authBeforeExecution = context.getAuthentication();
}
public void disableSaveOnResponseCommitted() {
disableOnResponseCommitted();
}
protected void saveContext(WarehouseUserContext context) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
HttpSession httpSession = request.getSession(false);
// See SEC-776
if (authentication == null || trustResolver.isAnonymous(authentication)) {
if (logger.isDebugEnabled()) {
logger.debug(
"WarehouseUserContext is empty or contents are anonymous - context will not be stored in HttpSession.");
}
if (httpSession != null) {
// SEC-1587 A non-anonymous context may still be in the
// session
// SEC-1735 remove if the contextBeforeExecution was not
// anonymous
httpSession.removeAttribute(WAREHOUSE_USER_CONTEXT_KEY);
}
return;
}
if (httpSession == null) {
httpSession = createNewSessionIfAllowed(context);
}
// If HttpSession exists, store current CustomerContext but only if
// it has
// actually changed in this thread (see SEC-37, SEC-1307, SEC-1528)
if (httpSession != null) {
// We may have a new session, so check also whether the context
// attribute
// is set SEC-1561
if (contextChanged(context) || httpSession.getAttribute(WAREHOUSE_USER_CONTEXT_KEY) == null) {
// httpSession.setAttribute(customerContextKey, context);
if (logger.isDebugEnabled()) {
logger.debug("WarehouseUserContext '" + context + "' stored to HttpSession: '" + httpSession);
}
}
}
}
private boolean contextChanged(WarehouseUserContext context) {
return true;
}
private HttpSession createNewSessionIfAllowed(WarehouseUserContext context) {
if (httpSessionExistedAtStartOfRequest) {
return null;
}
// Generate a HttpSession only if we need to
if (contextObject.equals(context)) {
return null;
}
try {
return request.getSession(true);
} catch (IllegalStateException e) {
logger.warn("Failed to create a session, as response has been committed. Unable to store"
+ " WarehouseUserContext.");
}
return null;
}
@Override
protected void onResponseCommitted() {
saveContext(WarehouseUserContextHolder.getContext());
}
@Override
public final String encodeRedirectUrl(String url) {
return super.encodeURL(url);
}
}
}
package com.beecode.inz.basis.context.warehouse;
import java.io.Serializable;
import com.beecode.inz.basis.pojo.WarehouseUser;
public interface WarehouseUserContext extends Serializable {
public WarehouseUser getWarehouseUser();
}
package com.beecode.inz.basis.context.warehouse;
public interface WarehouseUserContextConstants {
/**
* 当前用户
*/
public String CURRENT_WAREHOUSE_USER = "currentWarehouseUser";
}
package com.beecode.inz.basis.context.warehouse;
import org.springframework.util.Assert;
public class WarehouseUserContextHolder {
private static final ThreadLocal<WarehouseUserContext> contextHolder = new ThreadLocal<WarehouseUserContext>();
/**
* Explicitly clears the context value from the current thread.
*/
public static void clearContext() {
contextHolder.remove();
}
/**
* Obtain the current <code>SecurityContext</code>.
*
* @return the security context (never <code>null</code>)
*/
public static WarehouseUserContext getContext() {
WarehouseUserContext ctx = contextHolder.get();
if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}
return ctx;
}
/**
* Associates a new <code>SecurityContext</code> with the current thread of
* execution.
*
* @param context
* the new <code>SecurityContext</code> (may not be
* <code>null</code>)
*/
public static void setContext(WarehouseUserContext context) {
Assert.notNull(context, "Only non-null AminoContext instances are permitted");
contextHolder.set(context);
}
/**
* Delegates the creation of a new, empty context to the configured
* strategy.
*/
public static WarehouseUserContext createEmptyContext() {
return new WarehouseUserContextImpl();
}
}
package com.beecode.inz.basis.context.warehouse;
import com.beecode.inz.basis.pojo.WarehouseUser;
public class WarehouseUserContextImpl implements WarehouseUserContext {
/**
*
*/
private static final long serialVersionUID = 7659762847744346459L;
private WarehouseUser warehouseUser;
@Override
public WarehouseUser getWarehouseUser() {
return warehouseUser;
}
public void setWarehouseUser(WarehouseUser warehouseUser) {
this.warehouseUser = warehouseUser;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((warehouseUser == null) ? 0 : warehouseUser.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
WarehouseUserContextImpl other = (WarehouseUserContextImpl) obj;
if (warehouseUser == null) {
if (other.warehouseUser != null) {
return false;
}
} else if (!warehouseUser.equals(other.warehouseUser)) {
return false;
}
return true;
}
@Override
public String toString() {
return "WarehouseUserContextImpl [warehouseUser=" + warehouseUser + "]";
}
}
package com.beecode.inz.basis.context.warehouse;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.web.context.HttpRequestResponseHolder;
import org.springframework.web.filter.GenericFilterBean;
import com.beecode.amino.metadata.runtime.MetadataRuntime;
public class WarehouseUserContextPersistenceFilter extends GenericFilterBean {
static final String FILTER_APPLIED = "__warehouse_user_acpf_applied";
private final MetadataRuntime metadataRuntime;
private final WarehouseUserContextRepository repo;
private boolean forceEagerSessionCreation = false;
public WarehouseUserContextPersistenceFilter(MetadataRuntime metadataRuntime) {
this(metadataRuntime, new HttpSessionWarehouseUserContextRepository());
}
public WarehouseUserContextPersistenceFilter(MetadataRuntime metadataRuntime, WarehouseUserContextRepository repo) {
this.metadataRuntime = metadataRuntime;
this.repo = repo;
}
/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
if (request.getAttribute(FILTER_APPLIED) != null) {
// ensure that filter is only applied once per request
chain.doFilter(request, response);
return;
}
if (!metadataRuntime.isActive()) {
// TODO 元数据服务还没有启动好
return;
}
final boolean debug = logger.isDebugEnabled();
request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
if (forceEagerSessionCreation) {
HttpSession session = request.getSession();
if (debug && session.isNew()) {
logger.debug("Eagerly created session: " + session.getId());
}
}
HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response);
try {
WarehouseUserContext contextBeforeChainExecution = repo.loadContext(holder);
WarehouseUserContextHolder.setContext(contextBeforeChainExecution);
chain.doFilter(holder.getRequest(), holder.getResponse());
}
finally {
// Crucial removal of SecurityContextHolder contents - do this before anything
// else.
WarehouseUserContextHolder.clearContext();
request.removeAttribute(FILTER_APPLIED);
if (debug) {
logger.debug("WarehouseUserContextHolder now cleared, as request processing completed");
}
}
}
public void setForceEagerSessionCreation(boolean forceEagerSessionCreation) {
this.forceEagerSessionCreation = forceEagerSessionCreation;
}
}
package com.beecode.inz.basis.context.warehouse;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.context.HttpRequestResponseHolder;
public interface WarehouseUserContextRepository {
WarehouseUserContext loadContext(HttpRequestResponseHolder requestResponseHolder);
/**
* Allows the repository to be queried as to whether it contains a security context
* for the current request.
*
* @param request the current request
* @return true if a context is found for the request, false otherwise
*/
boolean containsContext(HttpServletRequest request);
}
package com.beecode.inz.basis.exception;
/**
* 无法找到指定用户 异常
* @author pengwufeng
*
*/
public class NotFoundWarehouseUserException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 3670197963486023974L;
public NotFoundWarehouseUserException() {
super();
}
public NotFoundWarehouseUserException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public NotFoundWarehouseUserException(String message, Throwable cause) {
super(message, cause);
}
public NotFoundWarehouseUserException(String message) {
super(message);
}
public NotFoundWarehouseUserException(Throwable cause) {
super(cause);
}
}
...@@ -8,6 +8,9 @@ import org.springframework.web.bind.annotation.RequestBody; ...@@ -8,6 +8,9 @@ import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.beecode.bcp.core.context.AminoContextHolder;
import com.beecode.bcp.type.KObject;
import com.beecode.inz.basis.context.warehouse.WarehouseUserContextHolder;
import com.beecode.inz.basis.pojo.WarehouseUser; import com.beecode.inz.basis.pojo.WarehouseUser;
import com.beecode.inz.basis.service.WarehouseUserService; import com.beecode.inz.basis.service.WarehouseUserService;
import com.beecode.inz.basis.team.pojo.ResponseObj; import com.beecode.inz.basis.team.pojo.ResponseObj;
...@@ -20,14 +23,14 @@ import com.beecode.xlib.utils.StringUtil; ...@@ -20,14 +23,14 @@ import com.beecode.xlib.utils.StringUtil;
* *
*/ */
@RestController @RestController
@RequestMapping("/warehouseuser") @RequestMapping("/warehouse/user")
public class WarehouseUserController { public class WarehouseUserController {
private static final Logger logger = LoggerFactory.getLogger(WarehouseUserController.class); private static final Logger logger = LoggerFactory.getLogger(WarehouseUserController.class);
@Autowired @Autowired
private WarehouseUserService warehouseUserService; private WarehouseUserService warehouseUserService;
/** /**
* 创建场站用户 * 创建场站用户
* *
...@@ -54,4 +57,19 @@ public class WarehouseUserController { ...@@ -54,4 +57,19 @@ public class WarehouseUserController {
return ResponseObj.success("操作成功",null); return ResponseObj.success("操作成功",null);
} }
/**
* 创建场站用户
*
* @param obj
* @return
*/
@PostMapping(value="test")
public Object test(@RequestBody String body) {
WarehouseUser user = WarehouseUserContextHolder.getContext().getWarehouseUser();
KObject staff = AminoContextHolder.getContext().getStaff();
return ResponseObj.success("操作成功",null);
}
} }
...@@ -12,4 +12,4 @@ com.beecode.inz.basis.config.BasisMapConfig,\ ...@@ -12,4 +12,4 @@ com.beecode.inz.basis.config.BasisMapConfig,\
com.beecode.inz.basis.config.CommonConfig,\ com.beecode.inz.basis.config.CommonConfig,\
com.beecode.inz.basis.config.MessageI18NConfiguration,\ com.beecode.inz.basis.config.MessageI18NConfiguration,\
com.beecode.inz.basis.config.OperationTeamConfig,\ com.beecode.inz.basis.config.OperationTeamConfig,\
com.beecode.inz.basis.config.CustomerContextConfiguration com.beecode.inz.basis.config.ContextConfiguration
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment