Commit 21c3e12b99088da494e6c377e60ff2af3e5e1ab6

Authored by jiangjiazhi
1 parent c6a1b775ac
Exists in master

add token inteceptor

Showing 11 changed files with 442 additions and 11 deletions

parent/core.sdk/src/main/java/com/lyms/annotation/TokenRequired.java View file @ 21c3e12
  1 +package com.lyms.annotation;
  2 +
  3 +
  4 +import java.lang.annotation.ElementType;
  5 +import java.lang.annotation.Retention;
  6 +import java.lang.annotation.RetentionPolicy;
  7 +import java.lang.annotation.Target;
  8 +
  9 +/**
  10 + * Created by Administrator on 2015/9/25 0025.
  11 + */
  12 +@Target({ElementType.TYPE, ElementType.METHOD})
  13 +@Retention(RetentionPolicy.RUNTIME)
  14 +public @interface TokenRequired
  15 +{
  16 +}
parent/core.sdk/src/main/java/com/lyms/constants/Constants.java View file @ 21c3e12
... ... @@ -13,5 +13,7 @@
13 13 public static final String CAPTCHA_TOKEN = "captcha_token";
14 14 public static final String CAPTCHA_FIELDNAME = "captcha";
15 15 public static final String CAPTCHA_CACHE = "captcha_cache";
  16 +
  17 + String AUTH_HEADER="Authorization";
16 18 }
parent/core.sdk/src/main/java/com/lyms/context/ContextHolder.java View file @ 21c3e12
  1 +package com.lyms.context;
  2 +
  3 +
  4 +
  5 +/**
  6 + * 上下文持有
  7 + *
  8 + * Created by Administrator on 2015/9/25 0025.
  9 + */
  10 +public class ContextHolder
  11 +{
  12 +
  13 + private static final ThreadLocal<PlatformContext> contextHolder =new ThreadLocal<PlatformContext>();
  14 +
  15 + public static PlatformContext getContext (){
  16 + PlatformContext context = contextHolder.get();
  17 + if(null==context){
  18 + throw new UnsupportedOperationException("请配置TokenRequired注解.");
  19 + }
  20 + return context;
  21 + }
  22 +
  23 + public static void setContext(PlatformContext context){
  24 + if(null == context){
  25 + throw new NullPointerException("context must not null.");
  26 + }
  27 + contextHolder.set(context);
  28 + }
  29 + public static void clean(){
  30 + contextHolder.remove();
  31 + }
  32 +}
parent/core.sdk/src/main/java/com/lyms/context/PlatformContext.java View file @ 21c3e12
  1 +package com.lyms.context;
  2 +
  3 +
  4 +/**
  5 + *
  6 + *
  7 + * Created by Administrator on 2015/9/25 0025.
  8 + */
  9 +public class PlatformContext
  10 +{
  11 +
  12 + private String token;
  13 +
  14 + private String userId;
  15 +
  16 + private String ipAddr;
  17 + //当前登录人所在的医院id
  18 + private String hospitalId;
  19 +
  20 + public String getHospitalId()
  21 + {
  22 + return hospitalId;
  23 + }
  24 +
  25 + public void setHospitalId(String hospitalId)
  26 + {
  27 + this.hospitalId = hospitalId;
  28 + }
  29 +
  30 + public String getUserId() {
  31 + return userId;
  32 + }
  33 +
  34 + public void setUserId(String userId) {
  35 + this.userId = userId;
  36 + }
  37 +
  38 + public String getToken() {
  39 + return token;
  40 + }
  41 +
  42 + public void setToken(String token) {
  43 + this.token = token;
  44 + }
  45 + public String getIpAddr() {
  46 + return ipAddr;
  47 + }
  48 +
  49 + public void setIpAddr(String ipAddr) {
  50 + this.ipAddr = ipAddr;
  51 + }
  52 +}
parent/core.sdk/src/main/java/com/lyms/util/IpUtils.java View file @ 21c3e12
  1 +package com.lyms.util;
  2 +
  3 +import javax.servlet.http.HttpServletRequest;
  4 +import java.net.InetAddress;
  5 +import java.net.UnknownHostException;
  6 +
  7 +/**
  8 + * 添加类的一句话简单描述。
  9 + * <p/>
  10 + * 详细描述
  11 + * <p/>
  12 + * 示例代码
  13 + * <pre>
  14 + * </pre/>
  15 + *
  16 + * @author JIAZHI.JIANG
  17 + * @version BME V100R001 2017-04-10 14:22
  18 + * @since BME V100R001C40B104
  19 + */
  20 +public class IpUtils
  21 +{
  22 +
  23 +
  24 + /**
  25 + * <li>@Description:获取客户端IP
  26 + * <li>@param request
  27 + * <li>@return
  28 + * <li>创建人:方承
  29 + * <li>创建时间:2016年11月26日
  30 + * <li>修改人:
  31 + * <li>修改时间:
  32 + */
  33 + public static final String getHost(HttpServletRequest request) {
  34 + String ip = request.getHeader("X-Forwarded-For");
  35 + if (StrUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
  36 + ip = request.getHeader("Proxy-Client-IP");
  37 + }
  38 + if (StrUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
  39 + ip = request.getHeader("WL-Proxy-Client-IP");
  40 + }
  41 + if (StrUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
  42 + ip = request.getHeader("X-Real-IP");
  43 + }
  44 + if (StrUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
  45 + ip = request.getRemoteAddr();
  46 + }
  47 + if ("127.0.0.1".equals(ip)) {
  48 + InetAddress inet = null;
  49 + try { // 根据网卡取本机配置的IP
  50 + inet = InetAddress.getLocalHost();
  51 + } catch (UnknownHostException e) {
  52 + e.printStackTrace();
  53 + }
  54 + ip = inet.getHostAddress();
  55 + }
  56 + // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  57 + if (ip != null && ip.length() > 15) {
  58 + if (ip.indexOf(",") > 0) {
  59 + ip = ip.substring(0, ip.indexOf(","));
  60 + }
  61 + }
  62 + return ip;
  63 + }
  64 +
  65 +}
parent/hospital.mac/src/main/java/com/lyms/hospital/service/token/TokenService.java View file @ 21c3e12
... ... @@ -7,9 +7,9 @@
7 7 {
8 8  
9 9  
10   - String createToken(Integer userId);
  10 + String createToken(String userId);
11 11  
12   - String createToken(Integer userId, Integer second);
  12 + String createToken(String userId, Integer second);
13 13  
14 14 boolean resetToken(String token);
15 15  
16 16  
17 17  
... ... @@ -17,11 +17,11 @@
17 17  
18 18 boolean validToken(String token, Integer second);
19 19  
20   - Integer getUserId(String token);
  20 + String getUserId(String token);
21 21  
22   - void deleteAllToken(Integer userId);
  22 + void deleteAllToken(String userId);
23 23  
24   - void deleteAllToken(Integer userId, String prefix);
  24 + void deleteAllToken(String userId, String prefix);
25 25  
26 26 void deleteToken(String token);
27 27  
parent/hospital.mac/src/main/java/com/lyms/hospital/service/token/impl/TokenServiceImpl.java View file @ 21c3e12
... ... @@ -47,7 +47,7 @@
47 47 }
48 48  
49 49 @Override
50   - public String createToken(Integer userId, Integer second)
  50 + public String createToken(String userId, Integer second)
51 51 {
52 52 String token = getPrefix() + TokenUtils.getToken(UUID.randomUUID().toString());
53 53  
... ... @@ -75,7 +75,7 @@
75 75 }
76 76  
77 77 @Override
78   - public String createToken(Integer userId)
  78 + public String createToken(String userId)
79 79 {
80 80 return createToken(userId, seconds);
81 81 }
82 82  
... ... @@ -111,13 +111,13 @@
111 111 }
112 112  
113 113 @Override
114   - public Integer getUserId(String token)
  114 + public String getUserId(String token)
115 115 {
116 116 Object obj = redisTemplate.opsForValue().get(token);
117 117 if (obj != null)
118 118 {
119 119 redisTemplate.opsForValue().set(token, SerializeUtils.serialize(obj), getSeconds());
120   - return (Integer) obj;
  120 + return (String) obj;
121 121 }
122 122 return null;
123 123 }
... ... @@ -129,7 +129,7 @@
129 129 }
130 130  
131 131 @Override
132   - public void deleteAllToken(Integer userId)
  132 + public void deleteAllToken(String userId)
133 133 {
134 134 String tempKey = getPrefix() + "_tokenlist_" + userId;
135 135 Object obj = redisTemplate.opsForValue().get(tempKey);
... ... @@ -142,7 +142,7 @@
142 142 }
143 143  
144 144 @Override
145   - public void deleteAllToken(Integer userId, String prefix)
  145 + public void deleteAllToken(String userId, String prefix)
146 146 {
147 147 String tempKey = prefix + "_tokenlist_" + userId;
148 148 Object obj = redisTemplate.opsForValue().get(tempKey);
parent/hospital.web/src/main/java/com/lyms/hospital/inteceptor/TokenValidateInteceptor.java View file @ 21c3e12
  1 +package com.lyms.hospital.inteceptor;
  2 +
  3 +
  4 +import com.lyms.annotation.TokenRequired;
  5 +import com.lyms.constants.Constants;
  6 +import com.lyms.context.ContextHolder;
  7 +import com.lyms.exception.LoginException;
  8 +import com.lyms.hospital.session.SessionProvider;
  9 +import com.lyms.web.controller.BaseController;
  10 +import org.apache.commons.lang.StringUtils;
  11 +import org.springframework.beans.factory.annotation.Autowired;
  12 +import org.springframework.web.method.HandlerMethod;
  13 +import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
  14 +
  15 +import javax.security.auth.login.LoginContext;
  16 +import javax.servlet.http.HttpServletRequest;
  17 +import javax.servlet.http.HttpServletResponse;
  18 +import java.lang.annotation.Annotation;
  19 +
  20 +/**
  21 + * 验证token拦截器
  22 + * <p>
  23 + * <ul>
  24 + * <li>
  25 + * 1、springmvc中配置TokenValidateInteceptor的拦截
  26 + * 2、在需要拦截的方法上面配置TokenRequired注解
  27 + * </li>
  28 + * </ul>
  29 + */
  30 +public class TokenValidateInteceptor extends HandlerInterceptorAdapter
  31 +{
  32 +
  33 + @Autowired
  34 + private SessionProvider sessionProvider;
  35 +
  36 + public static boolean isSiteController(Object handler) {
  37 + return handler instanceof HandlerMethod && (((HandlerMethod) handler).getBean() instanceof BaseController);
  38 + }
  39 +
  40 + @Override
  41 + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  42 +
  43 + if (!isSiteController(handler))
  44 + return true;
  45 + TokenRequired clientRequired = findAnnotation((HandlerMethod) handler, TokenRequired.class);
  46 + if (null == clientRequired)
  47 + return true;
  48 +
  49 + return validateToken(request, response);
  50 + }
  51 +
  52 + private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) {
  53 + T annotation = handler.getBeanType().getAnnotation(annotationType);
  54 + if (annotation != null)
  55 + return annotation;
  56 + return handler.getMethodAnnotation(annotationType);
  57 + }
  58 +
  59 + public boolean validateToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
  60 + String token = httpServletRequest.getHeader(Constants.AUTH_HEADER);
  61 + if (StringUtils.isEmpty(token)) {
  62 + throw new LoginException("miss auth.");
  63 + }
  64 + LoginContext loginContext = sessionProvider.checkSession(httpServletRequest, httpServletResponse, token);
  65 +
  66 + return true;
  67 + }
  68 +
  69 + /**
  70 + * This implementation is empty.
  71 + */
  72 + @Override
  73 + public void afterCompletion(
  74 + HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
  75 + throws Exception {
  76 + ContextHolder.clean();
  77 + }
  78 +}
parent/hospital.web/src/main/java/com/lyms/hospital/session/ISessionProvider.java View file @ 21c3e12
  1 +package com.lyms.hospital.session;
  2 +
  3 +import javax.security.auth.login.LoginContext;
  4 +import javax.servlet.http.HttpServletRequest;
  5 +import javax.servlet.http.HttpServletResponse;
  6 +
  7 +/**
  8 + *
  9 + * 提供验证session的方法
  10 + *
  11 + * Created by Administrator on 2016/6/2 0002.
  12 + */
  13 +public interface ISessionProvider
  14 +{
  15 +
  16 + /**
  17 + * 检查session
  18 + *
  19 + * @param request
  20 + * @param response
  21 + * @param token
  22 + * @return
  23 + */
  24 + boolean checkSession(HttpServletRequest request, HttpServletResponse response, String token);
  25 +
  26 + /**
  27 + * 删除session
  28 + * @param token
  29 + */
  30 + void removeSession(String token);
  31 +
  32 +}
parent/hospital.web/src/main/java/com/lyms/hospital/session/SessionProvider.java View file @ 21c3e12
  1 +package com.lyms.hospital.session;
  2 +
  3 +
  4 +import javax.security.auth.login.LoginContext;
  5 +import javax.servlet.http.HttpServletRequest;
  6 +import javax.servlet.http.HttpServletResponse;
  7 +import java.util.Map;
  8 +
  9 +/**
  10 + * session 能力提供
  11 + * <p>
  12 + * <p>
  13 + * Created by Administrator on 2016/6/2 0002.
  14 + */
  15 +public class SessionProvider implements ISessionProvider {
  16 + /**
  17 + * 配置
  18 + */
  19 + private Map<String, ISessionProvider> iSessionProviderMap;
  20 + /**
  21 + * 默认的session提供
  22 + */
  23 + private ISessionProvider defaultSessionProvider;
  24 + /**
  25 + * 当前策略
  26 + */
  27 + private String currentStrateger;
  28 +
  29 + public String getCurrentStrateger() {
  30 + return currentStrateger;
  31 + }
  32 +
  33 + public void setCurrentStrateger(String currentStrateger) {
  34 + this.currentStrateger = currentStrateger;
  35 + }
  36 +
  37 + public ISessionProvider getDefaultSessionProvider() {
  38 + return defaultSessionProvider;
  39 + }
  40 +
  41 + public void setDefaultSessionProvider(ISessionProvider defaultSessionProvider) {
  42 + this.defaultSessionProvider = defaultSessionProvider;
  43 + }
  44 +
  45 + public Map<String, ISessionProvider> getiSessionProviderMap() {
  46 + return iSessionProviderMap;
  47 + }
  48 +
  49 + public void setiSessionProviderMap(Map<String, ISessionProvider> iSessionProviderMap) {
  50 + this.iSessionProviderMap = iSessionProviderMap;
  51 + }
  52 +
  53 + @Override
  54 + public LoginContext checkSession(HttpServletRequest request, HttpServletResponse response, String token) {
  55 + ISessionProvider iSessionProvider = iSessionProviderMap.get(currentStrateger);
  56 + if (null != iSessionProvider) {
  57 + return iSessionProvider.checkSession(request, response, token);
  58 + }
  59 + if (null != defaultSessionProvider) {
  60 + return defaultSessionProvider.checkSession(request, response, token);
  61 + }
  62 + return null;
  63 + }
  64 +
  65 + @Override
  66 + public void removeSession(String token) {
  67 + ISessionProvider iSessionProvider = iSessionProviderMap.get(currentStrateger);
  68 + if (null != iSessionProvider) {
  69 + iSessionProvider.removeSession(token);
  70 + }
  71 + if (null != defaultSessionProvider) {
  72 + defaultSessionProvider.removeSession(token);
  73 + }
  74 + }
  75 +}
parent/hospital.web/src/main/java/com/lyms/hospital/session/strategy/LocalRedisSessionStrategy.java View file @ 21c3e12
  1 +package com.lyms.hospital.session.strategy;
  2 +
  3 +import com.lyms.base.common.entity.user.Users;
  4 +import com.lyms.base.common.service.user.UsersService;
  5 +import com.lyms.context.ContextHolder;
  6 +import com.lyms.context.PlatformContext;
  7 +import com.lyms.exception.LoginException;
  8 +import com.lyms.hospital.service.token.TokenService;
  9 +import com.lyms.hospital.session.ISessionProvider;
  10 +import com.lyms.util.IpUtils;
  11 +import org.apache.commons.lang.StringUtils;
  12 +import org.slf4j.Logger;
  13 +import org.slf4j.LoggerFactory;
  14 +import org.springframework.beans.factory.annotation.Autowired;
  15 +import org.springframework.stereotype.Component;
  16 +
  17 +import javax.servlet.http.HttpServletRequest;
  18 +import javax.servlet.http.HttpServletResponse;
  19 +
  20 +/**
  21 + * redis session 管理策越。
  22 + * <p/>
  23 + * 详细描述
  24 + * <p/>
  25 + * 示例代码
  26 + * <pre>
  27 + * </pre/>
  28 + *
  29 + * @author JIAZHI.JIANG
  30 + * @version BME V100R001 2017-04-10 11:14
  31 + * @since BME V100R001C40B104
  32 + */
  33 +@Component
  34 +public class LocalRedisSessionStrategy implements ISessionProvider
  35 +{
  36 +
  37 + //日志调测器
  38 + private static final Logger logger = LoggerFactory.getLogger(LocalRedisSessionStrategy.class);
  39 +
  40 + @Autowired
  41 + private TokenService tokenService;
  42 + @Autowired
  43 + private UsersService userService;
  44 +
  45 + @Override
  46 + public boolean checkSession(HttpServletRequest request, HttpServletResponse response, String token)
  47 + {
  48 + if (StringUtils.isEmpty(token))
  49 + {
  50 + throw new LoginException("");
  51 + }
  52 + String userId = tokenService.getUserId(token);
  53 +
  54 + if (StringUtils.isEmpty(userId))
  55 + {
  56 + throw new LoginException("");
  57 + }
  58 +
  59 + PlatformContext context = new PlatformContext();
  60 + context.setToken(token);
  61 + context.setUserId(userId);
  62 + context.setIpAddr(IpUtils.getHost(request));
  63 +
  64 + Users localUserService = userService.selectById(userId);
  65 + if (null == localUserService)
  66 + {
  67 + throw new LoginException("");
  68 + }
  69 + context.setHospitalId(localUserService.getOrgId());
  70 + ContextHolder.setContext(context);
  71 + return true;
  72 + }
  73 +
  74 + @Override
  75 + public void removeSession(String token)
  76 + {
  77 + tokenService.deleteToken(token);
  78 + }
  79 +}