Browse Source

请求验证

zhuth 7 years ago
parent
commit
cca7af8681

+ 1 - 8
src/main/java/com/uas/eis/controller/HelloWorldController.java

@@ -6,19 +6,13 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
-import com.uas.eis.dao.RoleDao;
-import com.uas.eis.entity.TokenConfig;
-import com.uas.eis.service.RoleService;
 import com.uas.eis.service.UserService;
-import com.uas.eis.utils.JwtUtil;
 
 @RestController
 public class HelloWorldController {
 
 	@Autowired
 	private UserService userService;
-	@Autowired
-	private RoleService roleService;
 	
 	@RequestMapping("/hello")
 	public String hello(){
@@ -35,8 +29,7 @@ public class HelloWorldController {
 	 */
 	@RequestMapping("/login")
 	public String login(String username, String password){
-		roleService.checkRoleEnable("zhuth");
-		return "<pre style=\"width:50%;font-family: mic;white-space: pre-wrap;word-wrap: break-word;\">"+roleService.login(username, password)+"</pre>";
+		return "<pre style=\"width:50%;font-family: mic;white-space: pre-wrap;word-wrap: break-word;\">"+userService.login(username, password)+"</pre>";
 	}
 	
 	/**

+ 7 - 1
src/main/java/com/uas/eis/core/WebAppConfig.java

@@ -1,5 +1,6 @@
 package com.uas.eis.core;
 
+import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@@ -10,8 +11,13 @@ import com.uas.eis.core.support.InterceptorConfig;
 @Configuration
 public class WebAppConfig extends WebMvcConfigurationSupport{
 
+	@Bean
+	public InterceptorConfig interceptorConfig(){
+		return new InterceptorConfig();
+	}
+	
 	public void addInterceptors(InterceptorRegistry registry){
-		registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/hello").excludePathPatterns("/login");
+		registry.addInterceptor(interceptorConfig()).addPathPatterns("/hello").excludePathPatterns("/login");
 //		registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/*").excludePathPatterns("/login");
 		registry.addInterceptor(new DataSourceInterceptor()).addPathPatterns("/*/**");
 	}

+ 31 - 7
src/main/java/com/uas/eis/core/support/InterceptorConfig.java

@@ -1,27 +1,35 @@
 package com.uas.eis.core.support;
 
+import java.util.Date;
+
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.ModelAndView;
 
+import com.uas.eis.service.UserService;
 import com.uas.eis.utils.BaseUtil;
 
 import io.jsonwebtoken.Claims;
 
 public class InterceptorConfig implements HandlerInterceptor{
 
+	@Autowired
+	private UserService userService;
+	
 	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
 		//token认证
 		String token = request.getParameter("token");
 		boolean flag = false;
 		String message = new String("程序错误");
 		if(token != null && !token.isEmpty()) { // 验证是否包含token
-			Claims claims = TokenHandler.checkToken(token); 
-			if(claims != null && claims.containsKey("userid")) { // 验证token信息是否合法
+			Claims claims = TokenHandler.parseToken(token); 
+			if(claims != null && checkToken(claims)) { // 验证token信息是否合法
 				String username = (String) claims.get("username");
-				if(checkRoleEnable(username)) {
+				String password = (String) claims.get("password");
+				if(checkUser(username, password)) { // 验证用户是否合法
 					String actionUrl = request.getRequestURI();
 					if(checkActionAccess(username, actionUrl)) { // 验证请求权限
 						flag = true;
@@ -32,7 +40,7 @@ public class InterceptorConfig implements HandlerInterceptor{
 					message = "请求用户无效";
 				}
 			}else {
-				message = "未通过验证的请求";
+				message = "Token未通过验证或已过期";
 			}
 		}else {
 			message = "未授权的请求";
@@ -51,11 +59,27 @@ public class InterceptorConfig implements HandlerInterceptor{
 			Exception ex) throws Exception {
 	}
 	
-	private boolean checkRoleEnable(String username) {
-		return true;
+	private boolean checkToken(Claims claims) {
+		Date now = new Date();
+		Date start = claims.getNotBefore();
+		Date end = claims.getExpiration();
+		
+		boolean flag = false;
+		if(now.after(start) || now.before(end)) {
+			flag = true;
+		}
+		return flag;
+	}
+	
+	private boolean checkUser(String username, String password) {
+		boolean enable = false;
+		if(username != null && password != null) {
+			enable = userService.checkUser(username, password);
+		}
+		return enable;
 	}
 	
 	private boolean checkActionAccess(String username, String action) {
-		return username.equals("zhuth") && action.equals("/test");
+		return userService.checkAction(username, action);
 	}
 }

+ 1 - 1
src/main/java/com/uas/eis/core/support/TokenHandler.java

@@ -10,7 +10,7 @@ public class TokenHandler {
 		return JwtUtil.createJWT(username, password);
 	}
 	
-	public static Claims checkToken(String token) {
+	public static Claims parseToken(String token) {
 		Claims claim = JwtUtil.parseJWT(token);
 		return claim;
 	}

+ 27 - 0
src/main/java/com/uas/eis/dao/BaseDao.java

@@ -22,6 +22,7 @@ import org.springframework.stereotype.Repository;
 import com.uas.eis.utils.BaseUtil;
 import com.uas.eis.utils.Constant;
 import com.uas.eis.utils.DateUtil;
+import net.sf.json.JSONObject;
 
 @Repository
 public class BaseDao{
@@ -553,4 +554,30 @@ public class BaseDao{
 		}
 	}
 	
+	public List<JSONObject> getFieldsJSONDatasByCondition(String tableName, String[] fields, String condition) {
+		StringBuffer sql = new StringBuffer("SELECT ");
+		sql.append(BaseUtil.parseArray2Str(fields, ","));
+		sql.append(" FROM ");
+		sql.append(tableName);
+		sql.append(" WHERE ");
+		sql.append(condition);
+		List<JSONObject> datas = new ArrayList<JSONObject>();
+		JSONObject obj = null;
+		Object value = null;
+		SqlRowList sl = queryForRowSet(sql.toString());
+		while (sl.next()) {
+			obj = new JSONObject();
+			for (int i = 0; i < fields.length; i++) {
+				value = sl.getObject(i + 1);
+				if (value != null && "TIMESTAMP".equals(value.getClass().getSimpleName().toUpperCase())) {
+					Timestamp time = (Timestamp) value;
+					value = DateUtil.parseDateToString(new Date(time.getTime()), "yyyy-MM-dd HH:mm:ss");
+				}
+				obj.put(fields[i], value);
+			}
+			datas.add(obj);
+		}
+		return datas;
+	}
+	
 }

+ 6 - 0
src/main/java/com/uas/eis/service/UserService.java

@@ -4,6 +4,12 @@ import java.util.Map;
 
 public interface UserService {
 
+	public abstract String login(String username, String password);
+	
 	public abstract Map<String, Object> getUser(String username);
+	
+	public abstract boolean checkUser(String username, String password);
+	
+	public abstract boolean checkAction(String username, String action);
 
 }

+ 35 - 1
src/main/java/com/uas/eis/serviceImpl/UserServiceImpl.java

@@ -1,24 +1,58 @@
 package com.uas.eis.serviceImpl;
 
+import java.util.List;
 import java.util.Map;
 
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
-import com.uas.eis.core.config.SpObserver;
+import com.uas.eis.core.support.TokenHandler;
 import com.uas.eis.dao.BaseDao;
 import com.uas.eis.service.UserService;
 
+import net.sf.json.JSONObject;
+
 @Service
 public class UserServiceImpl implements UserService {
 
 	@Autowired
 	private BaseDao baseDao;
 	
+	@Override
+	public String login(String username, String password) {
+		return TokenHandler.createToken(username, password);
+	}
+	
 	@Override
 	public Map<String, Object> getUser(String username){
 		//SpObserver.putSp("UAS_TEST");
 		return baseDao.getJdbcTemplate().queryForMap("select em_auditman from employee where em_name = ?",username);
 	}
 	
+	@Override
+	public boolean checkUser(String username, String password) {
+		return baseDao.checkIf("EIS_USER", "eu_enable=-1 and " + "eu_name='" + username + "' and eu_password='" + password + "'");
+	}
+
+	@Override
+	public boolean checkAction(String username, String action) {
+		boolean flag = false;
+		String roles = baseDao.queryForObject("select eu_role from eis_user where eu_name='" + username + "'", String.class);
+		String[] fields = {"er_reg","er_action"};
+		if(roles == null) {
+			return false;
+		}
+		List<JSONObject> res = baseDao.getFieldsJSONDatasByCondition("EIS_ROLE", fields, "er_id in (" + roles + ")");
+		for(int o = 0; o< res.size(); o++) {
+			JSONObject data = res.get(o);
+			String reg = data.containsKey("er_reg")?data.getString("er_reg"):"";
+			String act = data.containsKey("er_action")?data.getString("er_action"):"";
+			if(action.matches(reg) || act.indexOf(action) != -1) {
+				flag = true;
+				break;
+			}
+		}
+		return flag;
+	}
+	
 }

+ 0 - 2
src/main/java/com/uas/eis/utils/JwtUtil.java

@@ -21,7 +21,6 @@ public class JwtUtil {
 	public static String createJWT(String username, String password) {
 		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
 
-		UUID userid = UUID.randomUUID();
 		long nowMillis = System.currentTimeMillis();
 		Date now = new Date(nowMillis);
 
@@ -31,7 +30,6 @@ public class JwtUtil {
 
 		// 添加构成JWT的参数
 		JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
-				.claim("userid", userid)
 				.claim("username", username)
 				.claim("password", password)
 				.setIssuer(TokenConfig.ISSUER)