Commit c7a4bceb by zhanghj

V1.0.0--提交用户体现相关代码

git-svn-id: svn://192.168.3.233/frms/code/car-service/trunk/car-service@17284 aeb6102e-e053-11e5-9fec-f9ebc45caf4b
1 parent fbb770aa
Showing 24 changed files with 840 additions and 281 deletions
...@@ -21,6 +21,16 @@ ...@@ -21,6 +21,16 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId> <groupId>org.apache.httpcomponents</groupId>
......
/**
*
*/
package com.glsx.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @Title AuthCheck.java
* @Package com.glsx.common.annotation
* @Description TODO 登陆校验注解
* @author zhanghj
* @date 2019年1月31日 下午5:52:14
* @version 1.0.0
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthCheck {
boolean value() default true;
}
package com.glsx.common.config;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import feign.RequestInterceptor;
import feign.RequestTemplate;
@Configuration
public class FeignConfig implements RequestInterceptor{
private Logger logger = LoggerFactory.getLogger(FeignConfig.class);
@Override
public void apply(RequestTemplate template) {
// TODO Auto-generated method stub
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
template.header(name, values);
}
logger.info("feign interceptor header:{}",template);
}
}
}
...@@ -13,4 +13,6 @@ package com.glsx.common.constants; ...@@ -13,4 +13,6 @@ package com.glsx.common.constants;
public interface Constants { public interface Constants {
final static int OPERATION_INSERT = 1; final static int OPERATION_INSERT = 1;
final static int OPERATION_delete = 0; final static int OPERATION_delete = 0;
public static final String SESSION_USERNAME_KEY = "username";
} }
package com.glsx.common.constants;
/**
*
* @Title ResultCodeEnum.java
* @Package com.glsx.manager.constants
* @Description TODO
* @author zhanghj
* @date 2018年12月24日 下午5:31:38
* @version 1.0.0
*/
public enum ResultCodeEnum {
SUCCESS(200, "成功"),
FAIL(400, "失败"),
ERROR(500, "系统异常"),
PARAM_ERROR(100, "参数错误"),
NOT_LOGIN(101, "用户未登录"),
TRY_AGAIN(102, "失败,请重试"),
;
/**
*状态码
*/
private int code;
/**
* 状态码对应的信息
*/
private String msg;
ResultCodeEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.glsx.common.feign.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.alibaba.fastjson.JSONObject;
import com.glsx.common.config.FeignConfig;
/**
*
* @Title UserClient.java
* @Package com.glsx.common.feign.client
* @Description TODO feign的用户客户端
* @author zhanghj
* @date 2019年2月1日 上午11:06:44
* @version 1.0.0
*/
@FeignClient(name="car-service-usercenter", configuration=FeignConfig.class)
public interface UserClient {
//@RequestLine("GET /carservice/usercenter/user/isLogin")
@RequestMapping(method = RequestMethod.GET, value = "/carservice/usercenter/user/isLogin")
JSONObject isLogin();
}
package com.glsx.common.interceptor;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsx.common.annotation.AuthCheck;
import com.glsx.common.constants.Constants;
import com.glsx.common.constants.ResultCodeEnum;
import com.glsx.common.feign.client.UserClient;
/**
*
* @Title AuthInterceptor.java
* @Package com.glsx.manager.interceptor
* @Description TODO 登录校验拦截器
* @author zhanghj
* @date 2019年1月31日 下午5:51:25
* @version 1.0.0
*/
@Component
public class AuthInterceptor implements HandlerInterceptor {
private Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);
@Autowired
private UserClient userClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
//检查类上是否有校验登陆标注
Class<?> targetBean = handlerMethod.getBeanType();
AuthCheck authCheck = targetBean.getAnnotation(AuthCheck.class);
if(authCheck != null && authCheck.value()){
if(!sessionVerify(request)){
printNotLogin(response, request);
return false;
}
return true;
}
//检查方法上是否有校验登陆标注
authCheck = handlerMethod.getMethodAnnotation(AuthCheck.class);
if(authCheck != null && authCheck.value()){
if(!sessionVerify(request)){
printNotLogin(response, request);
return false;
}
}
return true;
}
private boolean sessionVerify(HttpServletRequest request) {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
boolean isLogin = false;
JSONObject result = userClient.isLogin();
if (result != null && result.getIntValue("code") == ResultCodeEnum.SUCCESS.getCode()) {
JSONObject data = result.getJSONObject("data");
isLogin = data.getBooleanValue("isLogin");
String username = data.getString(Constants.SESSION_USERNAME_KEY);
session.setAttribute(Constants.SESSION_USERNAME_KEY, username);
}
if (isLogin) {
return true;
}else {
return false;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
}
private void printNotLogin(HttpServletResponse response, HttpServletRequest request){
PrintWriter out = null;
Map<String, Object> result = new HashMap<String, Object>();
result.put("code", ResultCodeEnum.NOT_LOGIN.getCode());
result.put("msg", ResultCodeEnum.NOT_LOGIN.getMsg());
try {
response.setContentType("application/json;charset=utf-8");
out = response.getWriter();
out.print(JSON.toJSON(result));
} catch (IOException e) {
logger.error("获取PrintWriter异常", e);
} finally{
if(out != null){
out.close();
}
}
}
}
package com.glsx.common.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.glsx.common.constants.Constants;
/**
*
* @Title UserUtils.java
* @Package com.qurong.credit.sp.utils
* @Description TODO 获取当前用户工具类
* @author zhanghj
* @date 2018年7月16日 下午4:35:03
* @version
*/
public class UserUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(UserUtils.class.getName());
public static String getUserName(HttpServletRequest request) {
HttpSession session = request.getSession();
String username = (String) session.getAttribute(Constants.SESSION_USERNAME_KEY);
return username;
}
}
...@@ -42,18 +42,6 @@ ...@@ -42,18 +42,6 @@
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency> </dependency>
<!-- springboot使用Shiro框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring-boot-starter</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- Shiro使用EhCache缓存框架 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version>
</dependency>
<!-- hibernate.validator --> <!-- hibernate.validator -->
<dependency> <dependency>
<groupId>org.hibernate.validator</groupId> <groupId>org.hibernate.validator</groupId>
......
...@@ -7,6 +7,8 @@ import org.springframework.boot.builder.SpringApplicationBuilder; ...@@ -7,6 +7,8 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
/** /**
...@@ -20,8 +22,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; ...@@ -20,8 +22,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
*/ */
@SpringBootApplication @SpringBootApplication
@ComponentScan("com.glsx")
@ServletComponentScan @ServletComponentScan
@EnableEurekaClient @EnableEurekaClient
@EnableFeignClients(basePackages = {"com.glsx.common.feign.client"})
@EnableTransactionManagement @EnableTransactionManagement
@MapperScan(basePackages={"com.glsx.manager.mapper"}) @MapperScan(basePackages={"com.glsx.manager.mapper"})
public class Application extends SpringBootServletInitializer{ public class Application extends SpringBootServletInitializer{
......
package com.glsx.manager.config;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.Filter;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.glsx.common.utils.StringUtils;
import com.glsx.manager.shiro.UserRealm;
/**
*
* @Title ShiroConfig.java
* @Package com.glsx.manager.config
* @Description TODO shiro配置类
* @author zhanghj
* @date 2018年12月25日 下午3:41:47
* @version 1.0.0
*/
@Configuration
public class ShiroConfig {
public static final String PREMISSION_STRING = "perms[\"{0}\"]";
/**
* Session超时时间,单位为毫秒(默认30分钟)
*/
@Value("${shiro.session.expireTime}")
private int expireTime;
// 相隔多久检查一次session的有效性,单位毫秒,默认就是10分钟
@Value("${shiro.session.validationInterval}")
private int validationInterval;
// 验证码开关
@Value("${shiro.user.captchaEnabled}")
private boolean captchaEnabled;
// 验证码类型
@Value("${shiro.user.captchaType}")
private String captchaType;
// 设置Cookie的域名
@Value("${shiro.cookie.domain}")
private String domain;
// 设置cookie的有效访问路径
@Value("${shiro.cookie.path}")
private String path;
// 设置HttpOnly属性
@Value("${shiro.cookie.httpOnly}")
private boolean httpOnly;
// 设置Cookie的过期时间,秒为单位
@Value("${shiro.cookie.maxAge}")
private int maxAge;
// 登录地址
@Value("${shiro.user.loginUrl}")
private String loginUrl;
// 权限认证失败地址
@Value("${shiro.user.unauthorizedUrl}")
private String unauthorizedUrl;
/**
* 缓存管理器 使用Ehcache实现
*/
@Bean
public EhCacheManager getEhCacheManager() {
net.sf.ehcache.CacheManager cacheManager = net.sf.ehcache.CacheManager.getCacheManager("car_service_manager");
EhCacheManager em = new EhCacheManager();
if (StringUtils.isNull(cacheManager)) {
em.setCacheManagerConfigFile("classpath:ehcache/ehcache-shiro.xml");
return em;
} else {
em.setCacheManager(cacheManager);
return em;
}
}
/**
* 自定义Realm
*/
@Bean
public UserRealm userRealm(EhCacheManager cacheManager) {
UserRealm userRealm = new UserRealm();
userRealm.setCacheManager(cacheManager);
return userRealm;
}
/**
* 安全管理器
*/
@Bean
public DefaultWebSecurityManager securityManager(UserRealm userRealm) {
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
// 设置realm.
securityManager.setRealm(userRealm);
// 记住我
securityManager.setRememberMeManager(rememberMeManager());
// 注入缓存管理器;
securityManager.setCacheManager(getEhCacheManager());
// session管理器
//securityManager.setSessionManager(sessionManager());
return securityManager;
}
/**
* Shiro过滤器配置
*/
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// Shiro的核心安全接口,这个属性是必须的
shiroFilterFactoryBean.setSecurityManager(securityManager);
// 身份认证失败,则跳转到登录页面的配置
shiroFilterFactoryBean.setLoginUrl(loginUrl);
// 权限认证失败,则跳转到指定页面
shiroFilterFactoryBean.setUnauthorizedUrl(unauthorizedUrl);
// Shiro连接约束配置,即过滤链的定义
LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
// 对静态资源设置匿名访问
filterChainDefinitionMap.put("/favicon.ico**", "anon");
//对外开放api接口
filterChainDefinitionMap.put("/*/api/**", "anon");
// 退出 logout地址,shiro去清除session
//filterChainDefinitionMap.put("/logout", "logout");
// 不需要拦截的访问
filterChainDefinitionMap.put("/login", "anon");
// 系统权限列表
// filterChainDefinitionMap.putAll(SpringUtils.getBean(IMenuService.class).selectPermsAll());
Map<String, Filter> filters = new LinkedHashMap<>();
// 注销成功,则跳转到指定页面
//filters.put("logout", logoutFilter());
shiroFilterFactoryBean.setFilters(filters);
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
return shiroFilterFactoryBean;
}
/**
* cookie 属性设置
*/
public SimpleCookie rememberMeCookie() {
SimpleCookie cookie = new SimpleCookie("rememberMe");
cookie.setDomain(domain);
cookie.setPath(path);
cookie.setHttpOnly(httpOnly);
cookie.setMaxAge(maxAge * 24 * 60 * 60);
return cookie;
}
/**
* 记住我
*/
public CookieRememberMeManager rememberMeManager() {
CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
cookieRememberMeManager.setCookie(rememberMeCookie());
cookieRememberMeManager.setCipherKey(Base64.decode("fCq+/xW488hMTCD+cmJ3aQ=="));
return cookieRememberMeManager;
}
/**
* 开启Shiro注解通知器
*/
//@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
@Qualifier("securityManager") SecurityManager securityManager) {
AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
return authorizationAttributeSourceAdvisor;
}
}
package com.glsx.manager.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.glsx.common.interceptor.AuthInterceptor;
/**
*
* @Title WebConfig.java
* @Package com.glsx.manager.config
* @Description TODO 系统的配置相关文件,比如拦截器,过滤器
* @author zhanghj
* @date 2019年1月31日 下午5:51:54
* @version 1.0.0
*/
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Autowired
private AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor);
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void addFormatters(FormatterRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public void addReturnValueHandlers(
List<HandlerMethodReturnValueHandler> handlers) {
// TODO Auto-generated method stub
}
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public void extendHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public Validator getValidator() {
// TODO Auto-generated method stub
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
// TODO Auto-generated method stub
return null;
}
}
...@@ -4,6 +4,8 @@ import java.util.HashMap; ...@@ -4,6 +4,8 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.groups.Default; import javax.validation.groups.Default;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -14,13 +16,16 @@ import org.springframework.web.bind.annotation.RequestMethod; ...@@ -14,13 +16,16 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.glsx.common.annotation.AuthCheck;
import com.glsx.common.constants.ResultObject; import com.glsx.common.constants.ResultObject;
import com.glsx.common.utils.Page; import com.glsx.common.utils.Page;
import com.glsx.common.utils.UserUtils;
import com.glsx.manager.constants.ResultCodeEnum; import com.glsx.manager.constants.ResultCodeEnum;
import com.glsx.manager.pojo.Test; import com.glsx.manager.pojo.Test;
import com.glsx.manager.service.TestService; import com.glsx.manager.service.TestService;
import com.glsx.manager.utils.PropertiesUtil; import com.glsx.manager.utils.PropertiesUtil;
@AuthCheck
@RestController @RestController
@RequestMapping(value="/test") @RequestMapping(value="/test")
public class TestController extends BaseController{ public class TestController extends BaseController{
...@@ -40,7 +45,10 @@ public class TestController extends BaseController{ ...@@ -40,7 +45,10 @@ public class TestController extends BaseController{
@SuppressWarnings("resource") @SuppressWarnings("resource")
@RequestMapping(value="/list", method={RequestMethod.GET, RequestMethod.POST}) @RequestMapping(value="/list", method={RequestMethod.GET, RequestMethod.POST})
public ResultObject list(@RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "10") int pageSize){ public ResultObject list(@RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "10") int pageSize,
HttpServletRequest request, HttpSession session){
String username = UserUtils.getUserName(request);
logger.info("当前用户的用户名" + username);
Map<String, Object> result = new HashMap<String, Object>(); Map<String, Object> result = new HashMap<String, Object>();
Page page = new Page(pageIndex, pageSize); Page page = new Page(pageIndex, pageSize);
List<Test> list = testService.list(page); List<Test> list = testService.list(page);
......
package com.glsx.manager.shiro;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
public class UserRealm extends AuthorizingRealm{
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
// TODO Auto-generated method stub
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
String username = (String) token.getPrincipal();
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo("", "", getName());
return info;
}
}
...@@ -12,7 +12,7 @@ spring.jackson.date-format=yyyy-MM-dd HH:mm:ss ...@@ -12,7 +12,7 @@ spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8 spring.jackson.time-zone=GMT+8
#eurekaClient #eurekaClient
eureka.client.enabled=false eureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#\u5fc3\u8df3 #\u5fc3\u8df3
#eureka.instance.lease-renewal-interval-in-seconds=5 #eureka.instance.lease-renewal-interval-in-seconds=5
......
...@@ -86,26 +86,4 @@ spring.freemarker.suffix=.ftl ...@@ -86,26 +86,4 @@ spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates spring.freemarker.template-loader-path=classpath:/templates
#\u9759\u6001\u8d44\u6e90\u8def\u5f84 #\u9759\u6001\u8d44\u6e90\u8def\u5f84
spring.mvc.static-path-pattern=/**
##shiro\u914d\u7f6e
# \u767b\u5f55\u5730\u5740
shiro.user.loginUrl=/login
# \u6743\u9650\u8ba4\u8bc1\u5931\u8d25\u5730\u5740
shiro.user.unauthorizedUrl=/unauth
# \u8bbe\u7f6eCookie\u7684\u8fc7\u671f\u65f6\u95f4\uff0c\u5929\u4e3a\u5355\u4f4d
shiro.cookie.maxAge=30
# \u8bbe\u7f6eHttpOnly\u5c5e\u6027
shiro.cookie.httpOnly=false
# \u8bbe\u7f6ecookie\u7684\u6709\u6548\u8bbf\u95ee\u8def\u5f84
shiro.cookie.path=/
# \u8bbe\u7f6eCookie\u7684\u57df\u540d \u9ed8\u8ba4\u7a7a\uff0c\u5373\u5f53\u524d\u8bbf\u95ee\u7684\u57df\u540d
shiro.cookie.domain=
# \u9a8c\u8bc1\u7801\u5f00\u5173
shiro.user.captchaEnabled=false
# \u9a8c\u8bc1\u7801\u7c7b\u578b math \u6570\u7ec4\u8ba1\u7b97 char \u5b57\u7b26
shiro.user.captchaType=char
# \u76f8\u9694\u591a\u4e45\u68c0\u67e5\u4e00\u6b21session\u7684\u6709\u6548\u6027\uff0c\u9ed8\u8ba4\u5c31\u662f10\u5206\u949f
shiro.session.validationInterval=10
# Session\u8d85\u65f6\u65f6\u95f4\uff08\u9ed8\u8ba430\u5206\u949f\uff09
shiro.session.expireTime=30
\ No newline at end of file \ No newline at end of file
spring.mvc.static-path-pattern=/**
\ No newline at end of file \ No newline at end of file
...@@ -7,6 +7,8 @@ import org.springframework.boot.builder.SpringApplicationBuilder; ...@@ -7,6 +7,8 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan; import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.transaction.annotation.EnableTransactionManagement;
/** /**
...@@ -19,9 +21,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; ...@@ -19,9 +21,10 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
* @version 1.0.0 * @version 1.0.0
*/ */
@SpringBootApplication @SpringBootApplication
@ComponentScan("com.glsx")
@ServletComponentScan @ServletComponentScan
@EnableEurekaClient @EnableEurekaClient
@EnableTransactionManagement @EnableFeignClients(basePackages = {"com.glsx.common.feign.client"})
@MapperScan(basePackages={"com.glsx.ordercenter.mapper"}) @MapperScan(basePackages={"com.glsx.ordercenter.mapper"})
public class Application extends SpringBootServletInitializer{ public class Application extends SpringBootServletInitializer{
......
package com.glsx.ordercenter.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.glsx.common.interceptor.AuthInterceptor;
/**
*
* @Title WebConfig.java
* @Package com.glsx.manager.config
* @Description TODO 系统的配置相关文件,比如拦截器,过滤器
* @author zhanghj
* @date 2019年1月31日 下午5:51:54
* @version 1.0.0
*/
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Autowired
private AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor);
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void addFormatters(FormatterRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public void addReturnValueHandlers(
List<HandlerMethodReturnValueHandler> handlers) {
// TODO Auto-generated method stub
}
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public void extendHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public Validator getValidator() {
// TODO Auto-generated method stub
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
// TODO Auto-generated method stub
return null;
}
}
...@@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.RequestMethod; ...@@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.glsx.common.annotation.AuthCheck;
import com.glsx.common.constants.ResultObject; import com.glsx.common.constants.ResultObject;
import com.glsx.common.utils.Page; import com.glsx.common.utils.Page;
import com.glsx.ordercenter.constants.ResultCodeEnum; import com.glsx.ordercenter.constants.ResultCodeEnum;
...@@ -17,6 +18,7 @@ import com.glsx.ordercenter.pojo.Test; ...@@ -17,6 +18,7 @@ import com.glsx.ordercenter.pojo.Test;
import com.glsx.ordercenter.service.TestService; import com.glsx.ordercenter.service.TestService;
import com.glsx.ordercenter.utils.PropertiesUtil; import com.glsx.ordercenter.utils.PropertiesUtil;
@AuthCheck
@RestController @RestController
@RequestMapping(value="/test") @RequestMapping(value="/test")
public class TestController { public class TestController {
......
...@@ -5,6 +5,7 @@ spring.application.name=car-service-ordercenter ...@@ -5,6 +5,7 @@ spring.application.name=car-service-ordercenter
server.servlet.context-path=/carservice/ordercenter server.servlet.context-path=/carservice/ordercenter
server.port=8092 server.port=8092
#eurekaClient #eurekaClient
eureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#\u5fc3\u8df3 #\u5fc3\u8df3
#eureka.instance.lease-renewal-interval-in-seconds=5 #eureka.instance.lease-renewal-interval-in-seconds=5
......
package com.glsx.publicservice.config;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.glsx.common.interceptor.AuthInterceptor;
/**
*
* @Title WebConfig.java
* @Package com.glsx.manager.config
* @Description TODO 系统的配置相关文件,比如拦截器,过滤器
* @author zhanghj
* @date 2019年1月31日 下午5:51:54
* @version 1.0.0
*/
@Configuration
public class WebConfig implements WebMvcConfigurer{
@Autowired
private AuthInterceptor authInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor);
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
// TODO Auto-generated method stub
}
@Override
public void addFormatters(FormatterRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// TODO Auto-generated method stub
}
@Override
public void addArgumentResolvers(
List<HandlerMethodArgumentResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public void addReturnValueHandlers(
List<HandlerMethodReturnValueHandler> handlers) {
// TODO Auto-generated method stub
}
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// TODO Auto-generated method stub
}
@Override
public void configureHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public void extendHandlerExceptionResolvers(
List<HandlerExceptionResolver> resolvers) {
// TODO Auto-generated method stub
}
@Override
public Validator getValidator() {
// TODO Auto-generated method stub
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
// TODO Auto-generated method stub
return null;
}
}
package com.glsx.usercenter.controller; package com.glsx.usercenter.controller;
import com.github.pagehelper.PageHelper; import java.util.ArrayList;
import com.github.pagehelper.util.StringUtil; import java.util.HashMap;
import com.glsx.common.constants.ResultObject; import java.util.List;
import com.glsx.common.utils.DateUtil; import java.util.Map;
import com.glsx.common.utils.EncryptUtil;
import com.glsx.common.utils.Page;
import com.glsx.common.utils.StringUtils;
import com.glsx.usercenter.constants.ResultCodeEnum; import javax.servlet.http.HttpServletRequest;
import com.glsx.usercenter.pojo.user.*; import javax.servlet.http.HttpSession;
import com.glsx.usercenter.pojo.vo.UserQueryVo;
import com.glsx.usercenter.service.SysUserService;
import org.apache.shiro.SecurityUtils; import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationException;
...@@ -22,11 +17,28 @@ import org.apache.shiro.authc.UnknownAccountException; ...@@ -22,11 +17,28 @@ import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject; import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession; import com.github.pagehelper.PageHelper;
import java.util.*; import com.github.pagehelper.util.StringUtil;
import com.glsx.common.constants.ResultObject;
import com.glsx.common.utils.DateUtil;
import com.glsx.common.utils.EncryptUtil;
import com.glsx.common.utils.Page;
import com.glsx.common.utils.StringUtils;
import com.glsx.usercenter.constants.ResultCodeEnum;
import com.glsx.usercenter.pojo.user.SysManager;
import com.glsx.usercenter.pojo.user.SysMechanic;
import com.glsx.usercenter.pojo.user.SysMerchant;
import com.glsx.usercenter.pojo.user.SysResourceMatching;
import com.glsx.usercenter.pojo.user.SysUser;
import com.glsx.usercenter.pojo.vo.UserQueryVo;
import com.glsx.usercenter.service.SysUserService;
/** /**
* @author duanht * @author duanht
...@@ -328,6 +340,7 @@ public class UserController extends BaseController { ...@@ -328,6 +340,7 @@ public class UserController extends BaseController {
//String pwd = sysUserService.encryptPassword(username, password); //String pwd = sysUserService.encryptPassword(username, password);
UsernamePasswordToken token = new UsernamePasswordToken(username, password); UsernamePasswordToken token = new UsernamePasswordToken(username, password);
subject.login(token); subject.login(token);
session.setAttribute(com.glsx.common.constants.Constants.SESSION_USERNAME_KEY, username);
map.put("JSESSIONID", subject.getSession().getId()); map.put("JSESSIONID", subject.getSession().getId());
result.setData(map); result.setData(map);
} catch (UnknownAccountException uae) { } catch (UnknownAccountException uae) {
...@@ -372,11 +385,20 @@ public class UserController extends BaseController { ...@@ -372,11 +385,20 @@ public class UserController extends BaseController {
} }
@RequestMapping(value = "/isLogin", method = {RequestMethod.GET}) @RequestMapping(value = "/isLogin", method = {RequestMethod.GET})
public ResultObject isLogin() { public ResultObject isLogin(HttpSession session, HttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<String, Object>();
Subject subject = SecurityUtils.getSubject(); Subject subject = SecurityUtils.getSubject();
boolean isLogin = subject.isAuthenticated(); boolean isLogin = subject.isAuthenticated();
SysUser user = null;
String username = null;
if (isLogin) {
user = (SysUser) subject.getPrincipal();
if (user != null) {
username = user.getUsername();
}
}
map.put("isLogin", isLogin); map.put("isLogin", isLogin);
map.put(com.glsx.common.constants.Constants.SESSION_USERNAME_KEY, username);
return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), map); return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), map);
} }
......
...@@ -6,7 +6,7 @@ server.servlet.context-path=/carservice/usercenter ...@@ -6,7 +6,7 @@ server.servlet.context-path=/carservice/usercenter
server.port=8091 server.port=8091
#eurekaClient #eurekaClient
eureka.client.enabled=false eureka.client.enabled=true
eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/ eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
#\u5fc3\u8df3 #\u5fc3\u8df3
#eureka.instance.lease-renewal-interval-in-seconds=5 #eureka.instance.lease-renewal-interval-in-seconds=5
......
...@@ -57,6 +57,11 @@ ...@@ -57,6 +57,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<!-- feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
...@@ -98,9 +103,6 @@ ...@@ -98,9 +103,6 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- 如果没有该配置,devtools不会生效 -->
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</pluginManagement> </pluginManagement>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!